package com.rk.kbk.controller;

import com.alibaba.fastjson.JSONObject;
import com.rk.kbk.common.*;
import com.rk.kbk.controller.push.JpushClientUtil;
import com.rk.kbk.controller.push.JpushShopClientUtil;
import com.rk.kbk.controller.util.PayUtils;
import com.rk.kbk.controller.util.wxpay.util.WXpayCore;
import com.rk.kbk.controller.util.wxpay.util.WXpayXmlUtils;
import com.rk.kbk.dao.*;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.*;
import com.rk.kbk.service.OrderService;
import com.rk.kbk.service.UserService;
import com.rk.kbk.sms.SmsUtils;
import org.apache.commons.lang3.text.StrBuilder;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @OrderController
 * @订单Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/order")
public class OrderController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private UserDao userdao;
    @Autowired
    private CallSettingDao callSettingDao;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private UserService userService;
    @Autowired
    private CashRecordDao cashRecordDao;
    @Autowired
    private SortBetweenDao sortBetweenDao;
    @Autowired
    private ContactsDao contactsDao;
    @Autowired
    private DynamicPlaceDao dynamicPlaceDao;
    @Autowired
    private SqlToResult sqlToResult;
    @PersistenceContext
    private EntityManager entityManager;
    public static String wxnotify = "/api/order/wxpay/success";
    public static String wxnotify2 = "/api/payOver/wxpay/addTip";
    public static String wxnotify3= "/api/payOver/wxpay/changeOrder";

    private  final Lock lock = new ReentrantLock();
    /**
     * @新建订单
     * @param order
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateOrder",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateOrder(@RequestBody(required = false) Order order,String sortTypeIds,Long shopId) {
        log.debug("新建订单");
        User user = userdao.findOne(shopId);
        if(user.getShopStartTime()==null){
            return  JsonResp.fa("请先设置出货时间");
        }
        Address address = order.getAddressUser();
        log.debug("新建订单添加地址addressid................."+address.getId());
        if (null == address.getId() || 0==address.getId()) {//新增地址
            address.setType(1);
            address.setStatus(1);//地址设置为正常
            address.setLevel(0);//等级，默认0表示非默认地址，1表示默认地址
            address = addressDao.save(address);
            order.setAddressUser(address);
        } else {//老地址 比对一下省市区和详细地址  如果地址不同保存新地址  没修改不保存
            Address oldAddress = addressDao.findOne(address.getId());
            if(!oldAddress.equals(order.getAddressUser())) {
                address.setId(null);
                address.setStatus(1);//地址设置为正常
                address.setType(1);//客户地址
                address.setLevel(0);//等级，默认0表示非默认地址，1表示默认地址
                address = addressDao.save(address);
                order.setAddressUser(address);
            }
        }
        Address addressShop=addressDao.findOne(user.getAddress());
        //商家地址
        order.setAddressShop(addressShop);
        order.setShop(user);
        order.setOrderNumber(OrderUtils.getOrderNo());
        List<String> distanceList=MapUtils.manyDistance(address.getLng()+","+address.getLat(),addressShop.getLng()+","+addressShop.getLat());
        if(!distanceList.isEmpty()){
            order.setDistance(new BigDecimal(distanceList.get(0)).divide(new BigDecimal(1000),2,BigDecimal.ROUND_HALF_UP).toString());
        }
        //保存订单数据（小费、代收货款、订单备注、是否保温箱派送）
        order.setIsGoodsBad(0);//是否获取损坏
        order.setOrderStatus(0);//待抢订单
        order.setIsSendExcept(0);//是否收货异常
        order.setIsTakeExcept(0);//是否取货异常
        order.setAddSendMoney(0.00);//增加配送费用
        order.setDayOrderIndex(0);
        order.setIsCancelOrder(2);
        order.setChangeMoney(0.00);//变更费
        order.setTakeMoney(0D);//代收货款
        order.setAddSendTime(0);//增加配送时间
        /*****************************计算配送费用  开始**************************************/
      /*  String areaLength = order.getDistance();//距离
        String countyCode = addressDao.findOne(user.getAddress()).getAreaCode();
        Double sendMoney = null;Integer limitTime=null;//定义一个默认为null的配送费和限制配送时间
        List<SendRates> sendRatesList = sendRatesDao.findByAreaCodeOrderByAreaLengthAsc(countyCode);
        int i = 0, y = sendRatesList.size();
        for (; i < y; i++) {
            SendRates sendRates = sendRatesList.get(i);
            //如果距离比最大距离大
            if (Double.valueOf(sendRates.getAreaLength().toString()).compareTo(Double.valueOf(areaLength)) >= 0) {
                sendMoney = sendRates.getSendFee();
                limitTime=sendRates.getDeliverTime();
                break;
            }
            if(i==y-1){
                sendMoney = sendRates.getSendFee();
                limitTime=sendRates.getDeliverTime();
            }
        }*/
        Map map=orderService.findSendMoney(address.getLat(),address.getLng(),shopId);
        String sendMoney=String.valueOf(map.get("sendMoney"));
        String limitTime=String.valueOf(map.get("limitTime"));

        if(sendMoney.equals("-1")|| sendMoney.equals("-2")){
            return  JsonResp.fa("未计算出相应的配送费用，请核实该地区是否已经开通配送业务");
        }
            order.setSendMoney(Double.valueOf(sendMoney));//添加配送费
            order.setLimitTime(Integer.valueOf(limitTime));//添加限制配送时间
        /*****************************计算配送费用  结束**************************************/
        orderDao.save(order);
        //保存 货物类型
        String sortTypeId[] = sortTypeIds.split("\\*\\*\\*");
        List<SortBetween> sortBetweenList = new ArrayList<>();
        for (int i = 0; i < sortTypeId.length; i++) {
            SortBetween sb = new SortBetween();
            sb.setOrders(order);
            SortType st = new SortType();
            st.setId(Long.valueOf(sortTypeId[i]));
            sb.setSortTypeId(st);
            sb.setShop(user);
            sb.setType(1);
            sortBetweenList.add(sb);
        }
        sortBetweenDao.save(sortBetweenList);
        return JsonResp.ok(order.getId());
    }

    /**
     * @批量添加/修改订单
     * @param orders
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomeOrder",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomeOrder(@RequestBody List<Order> orders){
        log.debug("批量添加/修改订单");
        orderDao.save(orders);
        return JsonResp.ok();
    }


    /**
     * @  新建订单页面 中的信息（店铺名称、店铺电话、店铺地址）
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getShopMessage",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getShopMessage(Long shopId) {
        log.debug("获取店铺信息：店铺名称、店铺电话、店铺地址");
//        User user = userService.currentUser();
         User user=userdao.findOne(shopId);
        List<Order> orderList = orderDao.findByShop(user);
        String nickName = user.getNickName();
        String headUrl = user.getHeadUrl();
        String loginId = user.getPhone();
        String realName=user.getRealName();
        String contactTel=user.getContactTel();
        if(contactTel==null || "".equals(contactTel)){
            contactTel=loginId;
        }
       /* Double onTimeDeliveryRate=0.00;
        int takeOrderNum= 0,totalOrdersNum=0, overTimeOrderNum=0;
        int i = 0, y = orderList.size();
        for(;i< y;i++){
            Order order=orderList.get(i);
            int order_status=order.getOrderStatus();
            if(order_status!=0){
                ++totalOrdersNum;
                if (order.getIsTakeExcept() == 0) {
                    ++takeOrderNum;
                }
            }
        }
        //将小数转换为百分比
        NumberFormat num = NumberFormat.getPercentInstance();
        num.setMaximumIntegerDigits(3);
        num.setMaximumFractionDigits(2);
        String ontimeDeliveryRate="";
        if(orderList.isEmpty() || totalOrdersNum==0){
            ontimeDeliveryRate=100+"%";
        }else {
            ontimeDeliveryRate = num.format(new BigDecimal(overTimeOrderNum).divide(new BigDecimal(totalOrdersNum),2,BigDecimal.ROUND_HALF_UP));
        }*/
        Map map = new HashMap();
        if(user.getIsRegister()!=0){
            Address address = addressDao.findByIdAndStatus(user.getAddress(),1);//获取商家地址
            String shopAddress = address.getAddressDetail();
            map.put("lng", address.getLng());
            map.put("lat", address.getLat());
            map.put("shopAddress", shopAddress);
        }
        map.put("nickName", nickName);
        map.put("realName", realName);
        map.put("headUrl", headUrl);
        map.put("phone", loginId);
        map.put("contactTel", contactTel);
        String ontimeDeliveryRate=orderService.findOntimeDeliveryRate(user);
        map.put("onTimeDeliveryRate", ontimeDeliveryRate);
        return JsonResp.ok(map);
    }



    /**
     * @  个人资料联系电话修改(商家)
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/changeShopPhone",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp changeShopPhone(String phone,Long shopId){
        log.debug("个人资料联系电话修改(商家)");
//        Long shopId=userService.currentUserId();
//        JsonResp jsonResp=userService.findLoginUser();
//        List<Contacts> contactsList=contactsDao.findByPhone(phone);
            User user=userdao.findOne(shopId);
            user.setContactTel(phone);
            userdao.save(user);
            return JsonResp.ok();
    }


    /**
     * @  商家关闭订单（骑手上传货物损坏使用）
     *
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/shutDownOrder",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp shutDOwnOrder(Long orderId){
        log.debug("商家关闭订单（骑手上传货物损坏使用）");
        Order order=orderDao.findOne(orderId);
        order.setOrderLog("订单关闭，可能原因该订单已损坏");
        order.setOrderStatus(4);
        order.setSendDatetime(new Date());
        orderDao.save(order);
        return JsonResp.ok();
    }
    /**
     * @  商家确认支付
     *
     * @return 返回值JsonResp
     */
   /* @RequestMapping(value = "/payByShop",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getShopAccountMoneyAndTips(Long orderId){
        log.debug("商家支付：获取账户余额和账单费用");
        Order order=orderDao.findOne(orderId);
        User uer=order.getShop();
        Account account=accountDao.findByUser(uer);
        order.setAccount(account);
        return JsonResp.ok(order);
    }*/
    @RequestMapping(value = "/payByShop",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getShopAccountMoneyAndTips(Long orderId,String totalMoney,Long shopId,Integer type,HttpServletRequest request) {
        log.debug("商家支付：获取账户余额和账单费用");
        User user = userdao.findOne(shopId);
        Order order = orderDao.findOne(orderId);
        Integer dayOrderIndex = orderService.findDayOrderIndex(user);//日订单序号
        Double sendMoney = order.getSendMoney() == null ? 0.0 : order.getSendMoney();//配送费
        Double tip = order.getOrderTip() == null ? 0.0 : order.getOrderTip();//订单小费
        //Double takeMoney = order.getTakeMoney()==null?0.0:order.getTakeMoney();//代收货款
        Double changeMoney = order.getChangeMoney() == null ? 0.0 : order.getChangeMoney();//变更费
        Double goodsMoney = order.getGoodsMoney() == null ? 0.0 : order.getGoodsMoney();//货物价格
        BigDecimal payTotalMoney = new BigDecimal(String.valueOf(sendMoney)).add(new BigDecimal(String.valueOf(tip)));
        if (payTotalMoney.compareTo(new BigDecimal(totalMoney)) == 0) {
            Account account = accountDao.findByUser(user);
            Double allMoney = account.getAllMoney();//余额
            Double blockMoney = account.getBlockMoney();//冻结余额
            Double depositMoney = account.getDepositMoney();//押金
            if (new BigDecimal(depositMoney).compareTo(new BigDecimal("200")) < 0) {
                return JsonResp.fa("账户押金余额不足200，下单失败!");
            } else {
                String title = "";
                if (type == 1) {//如果用余额支付
                    //账户余额
                    if (new BigDecimal(allMoney).compareTo(payTotalMoney) < 0) {
                        return JsonResp.fa("账户余额不足");
                    }
                    Double saveAllMoney = new BigDecimal(allMoney).subtract(new BigDecimal(totalMoney)).doubleValue();
                    Double saveBlockMoney = new BigDecimal(blockMoney).add(new BigDecimal(totalMoney)).doubleValue();
                    account.setBlockMoney(saveBlockMoney);//将订单总费用保存到冻结余额中
                    account.setAllMoney(saveAllMoney);
                    accountDao.save(account);
                    title = "配送订单付款金额" + payTotalMoney + "元";
                    //保存余额支付记录
                    CashRecord cashRecord = new CashRecord();
                    cashRecord.setUser(user);
                    cashRecord.setTitle(title);
                    cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                    //  cashRecord.setOrderNumber();
                    cashRecord.setOrderType(1);//1表示配送订单，2表示商城订单，3表示其他
                    cashRecord.setOrderNumber(order.getOrderNumber());//订单编码
                    cashRecord.setRecoedType(3);//流水类型，1表示充值，2表示提现，3表示消费扣钱
                    cashRecord.setMoney(-payTotalMoney.doubleValue());
                    cashRecord.setMoneyType(1);
                    if (type == 1) {
                        cashRecord.setPayType(1);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                    } else if (type == 2) {
                        cashRecord.setPayType(2);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                    } else if (type == 3) {
                        cashRecord.setPayType(3);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                    }
                    cashRecord.setStatus(1);
                    cashRecord.setGivePerson(1);
                    cashRecordDao.save(cashRecord);//保存支付记录
                    order.setOrderStatus(1);
                    log.debug("余額支付成功。。。。。。。。。。。。。。。。。。。成功");
                    order.setDayOrderIndex(dayOrderIndex);
                    orderDao.save(order);
                } else if (type == 3) {//微信支付方式
                    String sym = request.getRequestURL().toString().split("/api/")[0];
                    String trade_no = (order.getId() + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0, 32);
                    Map map ;
                    map = PayUtils.WxPay(trade_no, payTotalMoney.doubleValue(), "支付", sym + wxnotify);
                    log.debug("新建訂單。。。。微信支付map="+map);
                    if (!map.isEmpty()) {
                        order.setDayOrderIndex(dayOrderIndex);
                        orderDao.save(order);
                        return JsonResp.ok("成功", map);
                    } else {
                        log.debug("微信支付失败");
                        throw new FailException();
                    }
                }


                if (type == 1) {
                    //----------消息推送给注册地址离商家地址5公里之内的所有全职骑手-----------------
                    //----------30s后如果该订单扔未抢则消息推送给所有兼职骑手----------------------
                    String msg_content = "有新的订单产生，请留意！";
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("type", 10);
                    jsonObject2.put("id", order.getId());
                    List aliasList = orderService.findAllAlaias(order, 1);
                    if (!aliasList.isEmpty()) {
                        int n = JpushClientUtil.sendToAliasId(aliasList, "新订单通知", "新订单", msg_content, jsonObject2.toString());
                        log.debug("新建订单推送给周围5公里内的骑手。状态n=" + n);
                    }
                    //-----------------------------开启定时任务，30s未抢推送给兼职骑手------------------
                    orderService.taskPush(order.getId());
                }

            }
            return JsonResp.ok();
        } else {
            return JsonResp.fa("金额错误！");
        }

    }

    @RequestMapping(value = "/wxpay/success",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public String wxpaySucc(HttpServletRequest request) throws IOException {
        System.out.println("微信支付回调");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultxml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = WXpayXmlUtils.xml2map(resultxml);
        outSteam.close();
        inStream.close();
        if (!WXpayCore.checkSign(params)) {
            // 支付失败
            return "fail";
        } else {
            System.out.println("===============付款成功==============");
            // ------------------------------
            // 处理业务开始
            // 此处处理订单状态，结合自己的订单数据完成订单状态的更新
            String total_fee = params.get("total_fee");
            double money = Double.valueOf(total_fee) / 100;
            Long orderId = Long.valueOf(params.get("out_trade_no").split("a")[0]);

           Order order=orderDao.findOne(orderId);
            User user=order.getShop();
            Integer userType=user.getUserType();
            order.setOrderStatus(1);
            orderDao.save(order);
            //----------消息推送给注册地址离商家地址5公里之内的所有全职骑手-----------------
            //----------30s后如果该订单扔未抢则消息推送给所有兼职骑手----------------------
            String msg_content="有新的订单产生，请留意！";
            JSONObject jsonObject2=new JSONObject();
            jsonObject2.put("type",10);
            jsonObject2.put("id",order.getId());
            List aliasList=orderService.findAllAlaias(order,1);
            if(!aliasList.isEmpty()){
                int n=JpushClientUtil.sendToAliasId(aliasList,"新订单通知","新订单",msg_content,jsonObject2.toString());
                log.debug("新建订单推送给周围5公里内的骑手。状态n="+n);
            }
            //-----------------------------开启定时任务，30s未抢推送给兼职骑手------------------
            orderService.taskPush(order.getId());
          /****************************支付明细**********************************/
            CashRecord cashRecord = new CashRecord();
            cashRecord.setUser(user);
            cashRecord.setTitle("配送订单付款金额"+money+"元");
            cashRecord.setTransactionNum(params.get("transaction_id"));//交易单号
            //  cashRecord.setOrderNumber();
            cashRecord.setOrderType(1);//1表示配送订单，2表示商城订单，3表示其他
            cashRecord.setOrderNumber(order.getOrderNumber());//订单编码
            cashRecord.setRecoedType(3);//流水类型，1表示充值，2表示提现，3表示消费扣钱
            cashRecord.setMoney(-money);
            cashRecord.setPayType(3);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
            cashRecord.setStatus(1);
            cashRecord.setGivePerson(1);
            cashRecordDao.save(cashRecord);//保存支付记录
            //updateUserPay(userId, String.valueOf(v));

            // 处理业务完毕
            // ------------------------------

            return "success";
        }
    }


    /**
     * @获取订单详情-ByOrderId（待抢订单、出货异常、收货异常）
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/orderDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findOrderDetailsByOrderId(Long orderId) {
        log.debug("获取订单详情-ByOrderId（待抢订单、出货异常、收货异常）");
        Order order = orderDao.findOne(orderId);
        Map map = new HashMap();
        User ride = order.getRide();
        /******************获取骑手资料 开始********************************/
        if (ride != null) {
            Map mapRide=new HashMap();
            mapRide.put("ridHeadUrl", ride.getHeadUrl());//骑手头像
            mapRide.put("rideRealName", ride.getRealName());
            List<Integer> orderStatusList=new ArrayList<>();
            orderStatusList.add(4);
            orderStatusList.add(6);
            orderStatusList.add(7);
           // orderStatusList.add(9);
            orderStatusList.add(10);
            //获取准时送达率
            List<Order> orderList = orderDao.findByRideAndOrderStatusIn(ride,orderStatusList);
            int ontimeDeliveryNum = 0;
            int i = 0, y = orderList.size(),totalOrdersNum=0;
            for (; i < y; i++) {
                Order timeOrder = orderList.get(i);
                if(timeOrder.getSendDatetime()!=null){
                    Date sendTime = timeOrder.getSendTime();
                    Date sendDateTime = timeOrder.getSendDatetime();
                   // int order_status=timeOrder.getOrderStatus();
                        ++totalOrdersNum;
                        if(sendDateTime.after(sendTime)){//如果送达日期时间小于规定送达日期时间
                            ++ontimeDeliveryNum;
                        }
                }
            }
            //将小数转换为百分比
            NumberFormat num = NumberFormat.getPercentInstance();
            num.setMaximumIntegerDigits(3);
            num.setMaximumFractionDigits(2);
            String ontimeDeliveryRate="";
            if(orderList.isEmpty()){
                ontimeDeliveryRate=100+"%";
            }else {
                ontimeDeliveryRate = num.format(new BigDecimal(ontimeDeliveryNum).divide(new BigDecimal(totalOrdersNum),4,BigDecimal.ROUND_HALF_UP));
            }

            mapRide.put("ontimeDeliveryRate", ontimeDeliveryRate);
            map.put("rideData",mapRide);
        }
        Address address = order.getAddressUser();
        Address shopAddress = order.getAddressShop();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("order", order);
        map.put("sendMoney", order.getSendMoney());
        map.put("changeMoney", order.getChangeMoney());
        map.put("orderTip", order.getOrderTip());
        map.put("isIncubatorDelivery", order.getIsIncubatorDelivery());
        map.put("takeMoney", order.getTakeMoney());
        map.put("userProvince", address.getProvince());//客户地址
        map.put("userLng", address.getLng());//客户地址经度
        map.put("userLat", address.getLat());//客户地址伟度
        map.put("userCity", address.getCity());//客户地址
        map.put("userCounty", address.getCounty());//客户地址
        map.put("userAddressDetail", address.getAddressDetail());//客户地址
        map.put("shopProvince", shopAddress.getProvince());//发货地址
        map.put("shopLng", shopAddress.getLng());//发货地址经度
        map.put("shopLat", shopAddress.getLat());//发货地址伟度
        map.put("shopCity", shopAddress.getCity());//发货地址
        map.put("shopCounty", shopAddress.getCounty());//发货地址
        map.put("shopAddressDetail", shopAddress.getAddressDetail());//发货地址
        map.put("realName", address.getRealName());
        map.put("sex", address.getSex());
        map.put("level", address.getLevel());//是否是默认地址
        if(order.getSendTime()!=null){
            map.put("sendTime", sdf.format(order.getSendTime()));//规定送达时间
        }else {
            map.put("sendTime", order.getSendTime());//规定送达时间
        }
        map.put("currentTime", sdf.format(new Date()));//当前时间
        Date uptDatetime = order.getUptDatetime();//修改时间
        if (uptDatetime == null) {
            map.put("uptDatetime", null);
        } else {
            sdf.format(order.getUptDatetime());
        }
        Date robDatetime = order.getRobDatetime();//骑手抢单时间
        if (robDatetime == null) {
            map.put("robDatetime", null);
        } else {
            map.put("robDatetime", sdf.format(order.getRobDatetime()));
        }
        Date getDatetime = order.getGetDatetime();//骑手取货时间
        if (getDatetime == null) {
            map.put("getDatetime", null);
        } else {
            map.put("getDatetime", sdf.format(order.getGetDatetime()));
        }
        Date sendDatetime = order.getSendDatetime();//送达时间/取消订单时间
        if (sendDatetime == null) {
            map.put("sendDatetime", null);
        } else {
            map.put("sendDatetime", sdf.format(order.getSendDatetime()));
        }
        map.put("isGoodsBad", order.getIsGoodsBad());//货物是否损坏,默认0表示正常,1表示损坏
        map.put("isSendexcept", order.getIsSendExcept());//是否收货异常,默认0表示不正常,1表示异常
        map.put("dayOrderIndex", order.getDayOrderIndex());
        //获取货物类型
        List<SortBetween> sortBetweenList = sortBetweenDao.findByOrders(order);
        List<String> sortTypeList = new ArrayList<>();
        for (int i = 0, y = sortBetweenList.size(); i < y; i++) {
            SortType sortType = sortBetweenList.get(i).getSortTypeId();
            sortTypeList.add(sortType.getSortName());
        }
        map.put("sortTypeList", sortTypeList);
        return JsonResp.ok(map);
    }

    /**
     * @增加小费重新发单（商家）
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/sendOrdeWithAddTip",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp sendOrdeWithAddTip(Long orderId,Double orderTip,Integer type,HttpServletRequest request) {
        log.debug("增加订单重新发单（商家）");
         Order order=orderDao.findOne(orderId);
          User user=order.getShop();
         order.setOrderTip(new BigDecimal(order.getOrderTip()).add(new BigDecimal(orderTip)).doubleValue());
         orderDao.save(order);
        //支付
          String title="";
           if(type==1){//余额支付
               Account account=accountDao.findByUser(order.getShop());
               Double allMoney = account.getAllMoney();//余额
               Double blockMoney=account.getBlockMoney();//冻结余额
               Double depositMoney=account.getDepositMoney();//押金
               if(account.getAllMoney().compareTo(orderTip)<0){
                   return JsonResp.fa("账户余额不足");
               }else {
                   //账户余额
                   Double saveAllMoney = new BigDecimal(allMoney).subtract(new BigDecimal(orderTip)).doubleValue();
                   Double saveBlockMoney=new BigDecimal(blockMoney).add(new BigDecimal(orderTip)).doubleValue();
                   account.setBlockMoney(saveBlockMoney);//将订单总费用保存到冻结余额中
                   account.setAllMoney(saveAllMoney);
                   accountDao.save(account);
                   //保存账户明细（余额支出）
                   CashRecord cashRecord=new CashRecord();
                   cashRecord.setUser(order.getShop());
                   cashRecord.setTitle("新增小费重新发单(余额支付"+orderTip+"元)");
                   cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());
                   cashRecord.setOrderType(1);
                   cashRecord.setOrderNumber(order.getOrderNumber());
                   cashRecord.setRecoedType(3);
                   // cashRecord.setRechargeType(5);
                   cashRecord.setMoney(-new BigDecimal(orderTip).doubleValue());
                   cashRecord.setStatus(2);
                   if(type==1){
                       cashRecord.setPayType(1);
                   }else if(type==2){
                       cashRecord.setPayType(2);
                   }else if(type==3){
                       cashRecord.setPayType(3);
                   }
                   cashRecord.setMoneyType(1);
                   cashRecord.setGivePerson(1);
                   cashRecordDao.save(cashRecord);
               }

           }else if(type==3){//微信支付方式
             /*  title="新增小费重新发单(微信支付"+orderTip+"元)";
               JSONObject jsonObject=new JSONObject();
               jsonObject.put("user",user);
               jsonObject.put("title",title);
               jsonObject.put("money",orderTip);
             //  jsonObject.put("userType",user.getUserType());
               jsonObject.put("payType",type);
               jsonObject.put("orderType",1);//1表示配送订单，2表示商城订单，3表示其他、4保险、5处罚
               jsonObject.put("orderNumber",order.getOrderNumber());
               jsonObject.put("recoedType",3);//流水类型，1充值 2提现 3消费 4收入5其他
               jsonObject.put("givePerson",1);*/
               String sym = request.getRequestURL().toString().split("/api/")[0];
               String trade_no = (order.getId() + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0,32);
               Map map;
//               String json=null;
               map = PayUtils.WxPay(trade_no, orderTip, "支付", sym + wxnotify2);
               if (!map.isEmpty()) {
                   return JsonResp.ok("成功", map);
               }else{
                   throw new FailException();
               }

                }

        return JsonResp.ok();
    }


    /**
     * @获取订单列表（商家）
     * @param orderStatus
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findOrderListByOrderStatus",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findOrderListByOrderStatus(String orderStatus,Long shopId,Integer pageNum, Integer pageSize) {
        log.debug("获取订单列表（商家）");
        User user=userdao.findOne(shopId);
        String orderStatusArr[]=orderStatus.split("\\*\\*\\*");
        List<Integer> orderStatusList=new ArrayList<>();
        for(int i=0;i<orderStatusArr.length;i++){
            orderStatusList.add(Integer.valueOf(orderStatusArr[i]));
        }
    //    List<Order> orderList=orderDao.findByShopAndOrderStatusInOrderByGmtDatetimeDescDayOrderIndexDesc(user,orderStatusList);
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
            page = orderDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                            expressions.add(cb.equal(root.get("shop"), user));
                        CriteriaBuilder.In<Object> stick = cb.in(root.get("orderStatus"));
                        for (Integer l : orderStatusList) {
                            expressions.add(stick.value(l));
                        }
                        return predicate;
                    }, pageable);

        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @确认取货（骑手）
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getOrder",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getOrder(Long orderId) throws ParseException {
        log.debug("确认取货（骑手）");
       Order order=orderDao.findOne(orderId);
        if(order.getOrderStatus()==2){ //订单处于待配送 才能点击确认取货
            order.setOrderStatus(3);//配送中
            order.setIsTakeExcept(0);
            order.setGetDatetime(new Date());
            order.setGetDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));//取货时间
            orderDao.save(order);
        }else {
            return  JsonResp.fa("订单错误！");
        }
        //激光推送
        List<String> aliasList=new ArrayList<>();
        aliasList.add(order.getShop().getAlias());
        String msg_content="骑手取货成功，订单正在配送中...";
        JSONObject jsonObject2=new JSONObject();
        jsonObject2.put("type",3);
        jsonObject2.put("id",order.getId());
       int n=JpushShopClientUtil.sendToAliasId(aliasList,"取货通知","取货成功",msg_content,jsonObject2.toString());
        return JsonResp.ok();
    }



    /**
     * @分页查询历史订单（已完成、已取消）
     * @param
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/history/order",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageOrderJpa(Long userId,Integer type, String dataTime,String orderStatus, Integer pageNum, Integer pageSize) throws ParseException {
        log.debug("分页查询订单(jpa方式)");
       // List orderStatusList = Arrays.asList(orderStatus.split(","));
        String selectSql = "SELECT a.id, a.day_order_index,a.order_number, a.send_money,a.order_tip,a.change_money,a.take_money,a.goods_money,a.order_mark,a.send_time,a.is_take_except,a.add_send_time,a.add_send_money,a.is_goods_bad,a.is_ok,a.except_log,a.gmt_datetime,a.rob_datetime," +
                " a.get_datetime,a.send_datetime,a.is_incubator_delivery,a.limit_time ,b.real_name AS user_real_name,b.phone AS user_phone,b.sex AS user_sex,b.province AS user_province,b.city as user_city,b.county AS user_county,b.address_detail AS user_address_detail"+
                " FROM orders a ,address b  WHERE a.address_user=b.id AND a.order_status IN(" + orderStatus + ")";


        String selectSql2= " SELECT a.id,a.day_order_index,a.order_number, a.send_money,a.order_tip,a.change_money,a.take_money,a.goods_money,a.order_mark,a.send_time,a.is_take_except,a.add_send_time,a.add_send_money,a.is_goods_bad,a.is_ok,a.except_log,a.gmt_datetime,a.rob_datetime," +
                " a.get_datetime,a.send_datetime,a.is_incubator_delivery,a.limit_time ,b.real_name AS shop_real_name,b.phone AS shop_phone,b.sex AS shop_sex,b.province AS shop_province,b.city as shop_city,b.county AS shop_county,b.address_detail AS shop_address_detail"+
                " FROM orders a ,address b WHERE a.address_shop=b.id  AND a.order_status IN(" + orderStatus + ")";

        if(type==1){//商家
            selectSql +=" AND  a.shop=" + userId ;
            selectSql2 +=" AND  a.shop=" + userId ;
        }else  if(type==2){//骑手
            selectSql +=" AND  a.ride=" + userId ;
            selectSql2 +=" AND  a.ride=" + userId ;
        }
        if (dataTime != null && !"".equals(dataTime)) {
            selectSql += " AND a.send_datetime like '%" + dataTime + "%'";
            selectSql2 += " AND a.send_datetime like '%" + dataTime + "%'";
        }
        String selectSq3="("+selectSql+")"+"AS a";
        String selectSq4="("+selectSql2+")"+"AS b";
        String sql3=" SELECT a.id,a.day_order_index,a.order_number, a.send_money,a.order_tip,a.change_money,a.take_money,a.goods_money,a.order_mark,a.send_time,a.is_take_except,a.add_send_time,a.add_send_money,a.is_goods_bad,a.is_ok,a.except_log,a.gmt_datetime,a.rob_datetime," +
                    " a.get_datetime,a.send_datetime,a.is_incubator_delivery,a.limit_time,a.user_real_name,a.user_phone,a.user_sex,a.user_province,a.user_city,a.user_county,a.user_address_detail,b.shop_real_name,b.shop_phone,b.shop_sex,b.shop_province ,"+
                    "b.shop_city,b.shop_county,b.shop_address_detail";

        String sql3_3=" FROM "+selectSq3+","+selectSq4+" WHERE a.id=b.id order by a.send_datetime desc";
        Query query = entityManager.createNativeQuery(sql3 + sql3_3);
        BigInteger count_number = null;
        //总记录数
        Query query_number = entityManager.createNativeQuery("SELECT COUNT(1) " + sql3_3);
        count_number = (BigInteger) query_number.getSingleResult();
        long total = count_number.longValue();
        //分页
        if ((pageNum - 1) >= 0) {
            query.setFirstResult((pageNum - 1) * pageSize);
        }
        if (pageSize > 0) {
            query.setMaxResults(pageSize);
        }
        entityManager.close();
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));
        return JsonResp.ok(new PageDto(pageNum, pageSize, mapList, total));
    }

    /**
     * @出货异常订单处理(驳回、同意)
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/dealSendExceptionOrder",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addSendMoneyAndSengTime(Long orderId,int type,Long shopId) {
        log.debug("出货异常订单处理(驳回、同意)");
        Order order = orderDao.findOne(orderId);
        User shop = userdao.findOne(shopId);
        if (order.getOrderStatus() == 5) {
            if (type == 0) {
                order.setIsRebut(0);//驳回
                order.setOrderStatus(2);
            } else if (type == 1) {
                order.setIsRebut(1);//同意
                User ride=order.getRide();
                Account account = accountDao.findByUser(shop);//商家账户
                Account accountRide=accountDao.findByUser(ride);//骑手账户
                if(order.getIsCancelOrder()==null){
                    return  JsonResp.fa("此订单有误");
                }else if(order.getIsCancelOrder()==1){//取消订单
                    Double sendMoney = order.getSendMoney();//配送费
                    Double tip = order.getOrderTip();//订单小费
                    Double changeMoney=order.getChangeMoney();//变更费
                    Double goodsMoney=order.getGoodsMoney();//货物价格
                    BigDecimal rideAddMoney=null;//骑手应该加的钱
                    BigDecimal  serviceMoney=null;//服务费
                    BigDecimal fTotalMoney= new BigDecimal(changeMoney).add(new BigDecimal(sendMoney)).add(new BigDecimal(tip));//总费用
                    rideAddMoney=fTotalMoney.multiply(new BigDecimal("0.5")).multiply(new BigDecimal(1-ride.getServiceRate())).setScale(1,BigDecimal.ROUND_HALF_UP);//小费和配送费的一半乘以服务费率
                    serviceMoney=fTotalMoney.multiply(new BigDecimal("0.5")).multiply(new BigDecimal(ride.getServiceRate())).setScale(1,BigDecimal.ROUND_HALF_UP);
                    Double rideSaveMoney= new BigDecimal(accountRide.getAllMoney()).add(rideAddMoney).doubleValue();
                    accountRide.setAllMoney(rideSaveMoney);
                    //将货物价格从骑手冻结押金中划回押金中
                    accountRide.setDepositMoney(new BigDecimal(accountRide.getDepositMoney()).add(new BigDecimal(goodsMoney)).doubleValue());
                    accountRide.setBlockDepositMoney(new BigDecimal(accountRide.getBlockDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
                    //将订单支付总费用从 冻结余额中划出
                    account.setBlockMoney(new BigDecimal(account.getBlockMoney()).subtract(fTotalMoney).doubleValue());
                    //将除去支付给骑手的费用外全部费用流回商家余额
                    BigDecimal saveShopAllMoney=fTotalMoney.multiply(new BigDecimal("0.5")).setScale(1,BigDecimal.ROUND_HALF_UP);
                    account.setAllMoney(new BigDecimal(account.getAllMoney()).subtract(saveShopAllMoney).doubleValue());
                    accountDao.save(accountRide);//保存到骑手账户余额
                    accountDao.save(account);//保存商家账户余额和冻结余额
                    order.setOrderStatus(9);
                    order.setSendDatetime(new Date());//取消订单时间
                    //激光推送
                    List<String> aliasList=new ArrayList<>();
                    aliasList.add(ride.getAlias());
                    String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                    String msg_content="您好，您有一条未配送的订单已被商家取消，取消订单时间:"+time;
                    JSONObject jsonObject2=new JSONObject();
                    jsonObject2.put("type",8);
                    jsonObject2.put("id",order.getId());
                    int n=JpushClientUtil.sendToAliasId(aliasList,"商家取消订单通知","取消订单成功",msg_content,jsonObject2.toString());
                    log.debug("推送给骑手状态"+n);
                    //-----------------------------钱包流水明细------------------
                    CashRecord cashRecord=new CashRecord();
                    String title="配送订单取消收款金额"+fTotalMoney.multiply(new BigDecimal("0.5")).setScale(1,BigDecimal.ROUND_HALF_UP)+"元（减半）"+"(平台服务费"+serviceMoney+"元)";
                    cashRecord.setTitle(title);
                    cashRecord.setOrderType(1);//配送订单
                    cashRecord.setOrderNumber(order.getOrderNumber());
                    cashRecord.setRecoedType(4);//配送订单得钱
                    cashRecord.setMoneyType(1);
                    cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                    cashRecord.setMoney(rideAddMoney.doubleValue());
                    cashRecord.setStatus(1);//成功
                    cashRecord.setGivePerson(1);
                    cashRecord.setReceivePerson(2);
                    cashRecordDao.save(cashRecord);
                    /*****************记录账户明细(押金加钱) 骑手**********************/
                    CashRecord depositMoneyCashRecord=new CashRecord();
                    depositMoneyCashRecord.setUser(ride);
                    depositMoneyCashRecord.setTitle("配送订单解冻金额"+goodsMoney+"元");
                    depositMoneyCashRecord.setOrderType(1);//配送订单
                    depositMoneyCashRecord.setOrderNumber(order.getOrderNumber());
                    depositMoneyCashRecord.setRecoedType(4);//配送订单得钱
                    depositMoneyCashRecord.setMoneyType(2);
                    depositMoneyCashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                    depositMoneyCashRecord.setMoney(goodsMoney);
                    depositMoneyCashRecord.setStatus(1);//成功
                    depositMoneyCashRecord.setGivePerson(2);
                    depositMoneyCashRecord.setReceivePerson(2);
                    cashRecordDao.save(depositMoneyCashRecord);
                    /*****************记录账户明细（余额加钱） 商家**********************/
                    CashRecord cashRecordShop=new CashRecord();
                    cashRecordShop.setUser(shop);
                    cashRecordShop.setOrderType(1);//配送订单
                    cashRecordShop.setOrderNumber(order.getOrderNumber());
                    cashRecordShop.setRecoedType(4);//消费扣钱
                    cashRecordShop.setMoneyType(1);
                    cashRecordShop.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                    String titl2="配送订单取消返还金额"+fTotalMoney.multiply(new BigDecimal("0.5").setScale(1,BigDecimal.ROUND_HALF_UP)).doubleValue()+"元（减半）";
                    cashRecordShop.setTitle(titl2);
                    cashRecordShop.setMoney(fTotalMoney.multiply(new BigDecimal("0.5").setScale(1,BigDecimal.ROUND_HALF_UP)).doubleValue());
                    cashRecordShop.setStatus(1);//成功
                    cashRecordShop.setReceivePerson(1);
                    cashRecordShop.setGivePerson(1);
                    cashRecordDao.save(cashRecordShop);

                }else if(order.getIsCancelOrder()==2){  //增加配送费和配送时间
                    if(account.getAllMoney().compareTo(order.getAddSendMoney())<0){
                        return  JsonResp.fa("账户余额不足");
                    }
                    //将骑手申请的增加的配送费增加到配送费中
                    Double addSendMoney = order.getAddSendMoney();
                    order.setSendMoney(new BigDecimal(addSendMoney).add(new BigDecimal(order.getSendMoney())).doubleValue());
                    order.setAddSendMoney(0.00);//归零
             /*   Double distance=Double.valueOf(order.getDistance());//送货距离
                //根据配送距离获取默认的增加时间3公里内45min 5km内60min 10km内90min
                int addTime=distance.compareTo(Double.valueOf(3))<=0?45:distance.compareTo(Double.valueOf(5))<=0?60:90;
                Long time = order.getSendTime().getTime() + order.getAddSendTime() * 60 * 1000+addTime* 60 * 1000;
                Integer limitTime =order.getLimitTime()+order.getAddSendTime();*/
                    //将骑手申请增加的配送费从商家余额中扣除
                    account.setAllMoney(new BigDecimal(account.getAllMoney()).subtract(new BigDecimal(addSendMoney)).doubleValue());
                    //将骑手申请增加的配送费增加到商家冻结余额中
                    account.setBlockMoney(new BigDecimal(account.getBlockMoney()).add(new BigDecimal(addSendMoney)).doubleValue());
                    order.setLimitTime(order.getLimitTime()+order.getAddSendTime());
                    Long time=order.getSendTime().getTime() + order.getAddSendTime() * 60 * 1000;
                    Integer limitTime =order.getLimitTime()+order.getAddSendTime();
                    try {
                        order.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)));
                        order.setLimitTime(limitTime);
                        order.setAddSendTime(0);//时间归零
                        order.setOrderStatus(2);//订单状态更改为待配送
                        //激光推送
                        List<String> aliasList=new ArrayList<>();
                        aliasList.add(order.getRide().getAlias());
                        String str="您有配送订单被变更，请注意查看！";
                        JSONObject jsonObject2=new JSONObject();
                        jsonObject2.put("type",6);
                        jsonObject2.put("id",order.getId());
                        int n= JpushClientUtil.sendToAliasId(aliasList,"订单更改通知","订单更改成功",str,jsonObject2.toString());
                        log.debug("订单更改通知推送消息状态码n="+n);
                        //-----------------------------钱包流水明细------------------
                        /*****************记录账户明细（增加配送费） 商家**********************/
                        CashRecord cashRecordShop=new CashRecord();
                        cashRecordShop.setUser(shop);
                        cashRecordShop.setOrderType(1);//配送订单
                        cashRecordShop.setOrderNumber(order.getOrderNumber());
                        cashRecordShop.setRecoedType(4);//消费扣钱
                        cashRecordShop.setMoneyType(1);
                        cashRecordShop.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                        String title2="配送订单出货异常付款金额"+addSendMoney+"元";
                        cashRecordShop.setTitle(title2);
                        cashRecordShop.setMoney(-addSendMoney);
                        cashRecordShop.setStatus(1);//成功
                        cashRecordShop.setReceivePerson(1);
                        cashRecordShop.setGivePerson(1);
                        cashRecordDao.save(cashRecordShop);
                    } catch (ParseException e) {
                        e.printStackTrace();
                        log.debug("出货异常订单处理(驳回)--时间转换错误！");
                    }
                    accountDao.save(account);
                }

            }
            orderDao.save(order);
        } else {
            return JsonResp.fa("订单id错误!");
        }

        return JsonResp.ok();
    }


    /**
     * @收货异常处理
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/receiveOrderException",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp receiveOrderException(Long orderId) {
        log.debug("收货异常处理");
        Order  order=orderDao.findOne(orderId);
        if(order.getOrderStatus()!=7){//如果不是收货异常
            return JsonResp.fa("订单id错误!");
        }
        Long sendTime=order.getSendTime().getTime();
        Long time=null,limitTime=null;
       if(order.getExceptLog()==1){//收货异常为地址错误
            time=sendTime+30*60*1000;
       }else if(order.getExceptLog()==2){//收货异常为电话号码错误
           time=sendTime+30*60*1000;
       }else if(order.getExceptLog()==3){//收货异常为电话无人接听
           time=sendTime+30*60*1000;
       }
       //重新设置规定送达时间
        try {
            order.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)));
            order.setLimitTime(order.getLimitTime()+30);
        } catch (ParseException e) {
            e.printStackTrace();
            log.debug("收货异常处理--时间格式转换错误");
        }
        order.setOrderStatus(3);//订单状态更改为配送中
        orderDao.save(order);
        //激光推送
        List<String> aliasList=new ArrayList<>();
     //   aliasList.add(order.getShop().getAlias());
        aliasList.add(order.getRide().getAlias());
        String str= null;
        try {
            str = "您有订单规定送达时间延至"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject2=new JSONObject();
        jsonObject2.put("type",7);
        jsonObject2.put("id",order.getId());
        int n= JpushClientUtil.sendToAliasId(aliasList,"收货异常处理通知","收货异常订单处理成功",str,jsonObject2.toString());
        System.out.print("收货异常消息推送给商家，消息状态n="+n);
        return JsonResp.ok();
    }
    /**
     * @骑手上传收货异常
     * @param orderId  exceptLog
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/uploadRreceiveOrderException",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp uploadRreceiveOrderException(Long orderId,int exceptLog) {
        log.debug("骑手上传收货异常");
        Order  order=orderDao.findOne(orderId);
        if(order.getOrderStatus()==3){//只有配送中才能申报收货异常
            order.setOrderStatus(7);//收货异常
            order.setExceptLog(exceptLog);
            order.setSendDatetime(new Date());
            order.setIsSendExcept(1);
            orderDao.save(order);
            //激光推送 发送抢单成功消息至骑手
            List<String> aliasList=new ArrayList<>();
            aliasList.add(order.getShop().getAlias());
            String str="";
            if(exceptLog==1){
                str="地址错误";
            }else  if(exceptLog==2){
                str="电话号码错误";
            } else if(exceptLog==3){
                str="电话无人接听";
            }
            String msg_content="您有一条订单存在收货异常，异常原因:"+str+"请尽快处理";
            JSONObject jsonObject2=new JSONObject();
            jsonObject2.put("type",13);
            jsonObject2.put("id",order.getId());
            int n= JpushShopClientUtil.sendToAliasId(aliasList,"收货异常通知","收货异常",msg_content,jsonObject2.toString());
            System.out.print("骑手上传收货异常，消息推送给商家，推送状态n="+n);
            //短信推送用户
             JSONArray phones=new JSONArray();
            phones.put(order.getAddressUser().getPhone());
          //  String phone=order.getAddressUser().getPhone();
            String templateid ="";//收货异常
            if(exceptLog==1){
                templateid="3057413";
            }else  if(exceptLog==2){
                templateid="3057413";
            } else if(exceptLog==3){
                templateid="3060373";
            }
            if(phones!=null){
                try {
                    SmsUtils.sendMsg(phones,templateid,null,2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


        }else {
            return JsonResp.fa("该订单不能上传收货异常");
        }
        return JsonResp.ok();
    }

    /**
     * @订单完成（骑手）
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/orderOver",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp orderOverByRide(Long orderId,Long rideId) {
        log.debug("订单完成（骑手） ");
        //开始加锁
        Order order = orderDao.findOne(orderId);
        lock.lock();
        log.debug("当前时间"+System.currentTimeMillis()+"当前线程"+Thread.currentThread().getName());
        try {
            if (order.getOrderStatus() != 3) {//只有配送中才能点击已完成
                return JsonResp.fa("该订单不能更改为已完成订单");
            } else {
                if (!order.getRide().getId().equals(rideId)) {//如果该订单的接单人不是登录骑手则返回错误信息
                    return JsonResp.fa("身份验证错误");
                }
                Double sendMoney = order.getSendMoney();
                Double tips = order.getOrderTip();
                //  Double takeMoney = order.getTakeMoney();//代收货款
                Double changeMoney = order.getChangeMoney();//变更费
                String goodsMoney = String.valueOf(order.getGoodsMoney());
                int n=order.getIsIncubatorDelivery();//是否代收
                //将小费和配送费加到骑手余额中
                Account account = accountDao.findByUser(order.getRide());
                Account accountShop = accountDao.findByUser(order.getShop());
                Double allMoney = account.getAllMoney();//骑手账户余额
                Double serviceRate=order.getRide().getServiceRate();//服务费率
                //判断送达时间是否超时 如果没有超时
                Long sendTime=order.getSendTime().getTime(),currentTime= System.currentTimeMillis();//规定送达时间戳和当前系统时间戳
                if (sendTime >= currentTime) {
                    Double fTotalMoney=new BigDecimal(String.valueOf(sendMoney)).add(new BigDecimal(String.valueOf(tips))).add(new BigDecimal(String.valueOf(changeMoney))).doubleValue();
                    BigDecimal  addMoney=new BigDecimal(fTotalMoney).multiply(new BigDecimal(1-serviceRate)).setScale(1,BigDecimal.ROUND_HALF_UP);
                    account.setAllMoney(new BigDecimal(String.valueOf(allMoney)).add(addMoney).doubleValue());
                    //骑手押金返回
                    if(n==1){
                        account.setDepositMoney(new BigDecimal(String.valueOf(account.getDepositMoney())).add(new BigDecimal(goodsMoney)).doubleValue());
                    }
                    account.setBlockDepositMoney(new BigDecimal(String.valueOf(account.getBlockDepositMoney())).subtract(new BigDecimal(goodsMoney)).doubleValue());

                    //商家从冻结余额中接订单的总费用减掉
                    Double blockMoney = accountShop.getBlockMoney();
                    accountShop.setBlockMoney(new BigDecimal(String.valueOf(blockMoney)).subtract(new BigDecimal(fTotalMoney)).doubleValue());
                    //代收货款 回归
                    if(n==0){
                        accountShop.setAllMoney(new BigDecimal(String.valueOf(accountShop.getAllMoney())).add(new BigDecimal(goodsMoney)).doubleValue());
                    }
                    accountDao.save(account);
                    accountDao.save(accountShop);
                    /*****************记录账户明细(骑手完成订单) 骑手**********************/
                    CashRecord cashRecordRide = new CashRecord();
                    cashRecordRide.setUser(order.getRide());
                    //String title="配送费"+sendMoney+"+变更费"+changeMoney+"+小费"+tips+"-平台服务费"+new BigDecimal(fTotalMoney).multiply(new BigDecimal(serviceRate)).setScale(2,BigDecimal.ROUND_HALF_UP);
                    String title="配送订单完成收款金额"+fTotalMoney+"元"+"(平台服务费"+new BigDecimal(fTotalMoney).multiply(new BigDecimal(serviceRate)).setScale(1,BigDecimal.ROUND_HALF_UP)+"元)";
                    cashRecordRide.setTitle(title);
                    cashRecordRide.setOrderType(1);//配送订单
                    cashRecordRide.setOrderNumber(order.getOrderNumber());
                    cashRecordRide.setRecoedType(4);//配送订单得钱
                    cashRecordRide.setMoneyType(1);
                    cashRecordRide.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                    cashRecordRide.setMoney(addMoney.doubleValue());
                    cashRecordRide.setStatus(1);//成功
                    cashRecordRide.setReceivePerson(2);
                    cashRecordRide.setGivePerson(1);
                    cashRecordDao.save(cashRecordRide);
                    if(n==1){
                        /*****************记录账户明细(押金回退) 骑手**********************/
                        CashRecord cashRecordRide2 = new CashRecord();
                        cashRecordRide2.setUser(order.getRide());
                        cashRecordRide2.setTitle("配送订单解冻金额"+goodsMoney+"元");
                        cashRecordRide2.setOrderType(1);//配送订单
                        cashRecordRide2.setOrderNumber(order.getOrderNumber());
                        cashRecordRide2.setRecoedType(4);//配送订单得钱
                        cashRecordRide2.setMoneyType(2);
                        cashRecordRide2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                        cashRecordRide2.setMoney(Double.valueOf(goodsMoney));
                        cashRecordRide2.setStatus(1);//成功
                        cashRecordRide2.setReceivePerson(2);
                        cashRecordRide2.setGivePerson(2);
                        cashRecordDao.save(cashRecordRide2);
                    }
                    if(n==0){
                        CashRecord cashRecordRide2 = new CashRecord();
                        cashRecordRide2.setUser(order.getRide());
                        cashRecordRide2.setTitle("配送订单解冻金额"+goodsMoney+"元");
                        cashRecordRide2.setOrderType(1);//配送订单
                        cashRecordRide2.setOrderNumber(order.getOrderNumber());
                        cashRecordRide2.setRecoedType(4);//配送订单得钱
                        cashRecordRide2.setMoneyType(2);
                        cashRecordRide2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                        cashRecordRide2.setMoney(Double.valueOf(goodsMoney));
                        cashRecordRide2.setStatus(1);//成功
                        cashRecordRide2.setReceivePerson(2);
                        cashRecordRide2.setGivePerson(2);
                        cashRecordDao.save(cashRecordRide2);
                        CashRecord cashRecordRide3 = new CashRecord();
                        cashRecordRide3.setUser(order.getRide());
                        cashRecordRide3.setTitle("配送订单代收货款金额"+goodsMoney+"元");
                        cashRecordRide3.setOrderType(1);//配送订单
                        cashRecordRide3.setOrderNumber(order.getOrderNumber());
                        cashRecordRide3.setRecoedType(3);//配送订单得钱
                        cashRecordRide3.setMoneyType(2);
                        cashRecordRide3.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                        cashRecordRide3.setMoney(-Double.valueOf(goodsMoney));
                        cashRecordRide3.setStatus(1);//成功
                        cashRecordRide3.setReceivePerson(1);
                        cashRecordRide3.setGivePerson(2);
                        cashRecordDao.save(cashRecordRide3);
                        /*****************在账户流程表中做金额流向记录(代收货款)  商家**********************/
                        CashRecord cashRecordShop = new CashRecord();
                        cashRecordShop.setUser(order.getShop());
                        cashRecordShop.setTitle("配送订单代收货款金额"+goodsMoney+"元");
                        cashRecordShop.setOrderType(1);//配送订单
                        cashRecordShop.setOrderNumber(order.getOrderNumber());
                        cashRecordShop.setRecoedType(4);//收入
                        cashRecordShop.setMoneyType(1);
                        cashRecordShop.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                        cashRecordShop.setMoney(Double.valueOf(goodsMoney));
                        cashRecordShop.setStatus(1);//成功
                        cashRecordShop.setGivePerson(2);
                        cashRecordShop.setReceivePerson(1);
                        cashRecordDao.save(cashRecordShop);
                    }

                } else {//超时处罚
                    Long overTime = currentTime-sendTime;
                    if (overTime <= 15 * 60*1000) {//超出15min扣除一半费用
                        Double st = new BigDecimal(String.valueOf(sendMoney)).add(new BigDecimal(String.valueOf(tips))).add(new BigDecimal(String.valueOf(changeMoney))).doubleValue();
                        BigDecimal saveMoney=new BigDecimal(st).multiply(new BigDecimal("0.5")).multiply(new BigDecimal(1-serviceRate)).setScale(1,BigDecimal.ROUND_HALF_UP);
                        account.setAllMoney(new BigDecimal(String.valueOf(allMoney)).add(saveMoney).doubleValue());
                        //骑手押金回归
                        if(n==1){
                            account.setDepositMoney(new BigDecimal(account.getDepositMoney()).add(new BigDecimal(goodsMoney)).doubleValue());
                        }
                        account.setBlockDepositMoney(new BigDecimal(account.getBlockDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
                        accountDao.save(account);
                        //商家从冻结余额中接订单的总费用减掉
                        accountShop.setBlockMoney(new BigDecimal(String.valueOf(accountShop.getBlockMoney())).subtract(new BigDecimal(st)).doubleValue());
                        //商家余额中加上一半费用
                        BigDecimal leftMoney=new BigDecimal(st).multiply(new BigDecimal("0.5")).setScale(1,BigDecimal.ROUND_HALF_UP);
                        if(n==0){
                            accountShop.setAllMoney(new BigDecimal(String.valueOf(accountShop.getAllMoney())).add(leftMoney).add(new BigDecimal(goodsMoney)).doubleValue());
                        }else if(n==1){
                            accountShop.setAllMoney(new BigDecimal(String.valueOf(accountShop.getAllMoney())).add(leftMoney).doubleValue());
                        }
                        accountDao.save(accountShop);
                        /****************************账户资金流水明细  骑手*****************************/
                        CashRecord cashRecordRide = new CashRecord();
                        cashRecordRide.setUser(order.getRide());
                 /*   String str="配送费"+new BigDecimal(sendMoney).multiply(new BigDecimal("0.5")).setScale(2,BigDecimal.ROUND_HALF_UP)+"+变更费"
                            +new BigDecimal(changeMoney).multiply(new BigDecimal("0.5")).setScale(2,BigDecimal.ROUND_HALF_UP)+"+小费"
                            +new BigDecimal(tips).multiply(new BigDecimal("0.5")).setScale(2,BigDecimal.ROUND_HALF_UP)+"-平台服务费"
                            +new BigDecimal(st).multiply(new BigDecimal("0.5")).multiply(new BigDecimal(serviceRate));*/
                        String  str="配送订单完成超时收款金额"+new BigDecimal(st).multiply(new BigDecimal("0.5")).setScale(1,BigDecimal.ROUND_HALF_UP)+"元（减半）"+
                                "(平台服务费"+new BigDecimal(st).multiply(new BigDecimal("0.5")).multiply(new BigDecimal(serviceRate)).setScale(1,BigDecimal.ROUND_HALF_UP)+"元)";
                        cashRecordRide.setTitle(str);
                        cashRecordRide.setOrderType(1);//配送订单
                        cashRecordRide.setOrderNumber(order.getOrderNumber());
                        cashRecordRide.setRecoedType(4);//配送订单得钱
                        cashRecordRide.setMoneyType(1);
                        cashRecordRide.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                        cashRecordRide.setMoney(saveMoney.doubleValue());
                        cashRecordRide.setStatus(1);//成功
                        cashRecordRide.setReceivePerson(2);
                        cashRecordRide.setGivePerson(1);
                        cashRecordDao.save(cashRecordRide);
                        if(n==1){
                            /****************************账户资金流水明细(骑手完成订单押金回归)  骑手***************/
                            CashRecord cashRecordRide2 = new CashRecord();
                            cashRecordRide2.setUser(order.getRide());
                            cashRecordRide2.setTitle("配送订单解冻金额"+goodsMoney+"元");
                            cashRecordRide2.setOrderType(1);//配送订单
                            cashRecordRide2.setOrderNumber(order.getOrderNumber());
                            cashRecordRide2.setRecoedType(4);//配送订单得钱
                            cashRecordRide2.setMoneyType(2);
                            cashRecordRide2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                            cashRecordRide2.setMoney(Double.valueOf(goodsMoney));
                            cashRecordRide2.setStatus(1);//成功
                            cashRecordRide2.setReceivePerson(2);
                            cashRecordRide2.setGivePerson(2);
                            cashRecordDao.save(cashRecordRide2);
                        }

                        /****************************账户资金流水明细(一半费用回归余额)  商家***************/
                        CashRecord cashRecordShop = new CashRecord();
                        cashRecordShop.setUser(order.getShop());
                        cashRecordShop.setTitle("配送订单完成超时返还金额"+leftMoney+"元（减半）" );
                        cashRecordShop.setOrderType(1);//配送订单
                        cashRecordShop.setOrderNumber(order.getOrderNumber());
                        cashRecordShop.setRecoedType(4);//消费
                        cashRecordShop.setMoneyType(1);
                        cashRecordShop.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                        cashRecordShop.setMoney(leftMoney.doubleValue());
                        cashRecordShop.setStatus(1);//成功
                        cashRecordShop.setGivePerson(1);
                        cashRecordShop.setReceivePerson(1);
                        cashRecordDao.save(cashRecordShop);
                        if(n==0){
                            CashRecord cashRecordRide2 = new CashRecord();
                            cashRecordRide2.setUser(order.getRide());
                            cashRecordRide2.setTitle("配送订单解冻金额"+goodsMoney+"元");
                            cashRecordRide2.setOrderType(1);//配送订单
                            cashRecordRide2.setOrderNumber(order.getOrderNumber());
                            cashRecordRide2.setRecoedType(4);//配送订单得钱
                            cashRecordRide2.setMoneyType(2);
                            cashRecordRide2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                            cashRecordRide2.setMoney(Double.valueOf(goodsMoney));
                            cashRecordRide2.setStatus(1);//成功
                            cashRecordRide2.setReceivePerson(2);
                            cashRecordRide2.setGivePerson(2);
                            cashRecordDao.save(cashRecordRide2);
                            CashRecord cashRecordRide3 = new CashRecord();
                            cashRecordRide3.setUser(order.getRide());
                            cashRecordRide3.setTitle("配送订单代收货款金额"+goodsMoney+"元");
                            cashRecordRide3.setOrderType(1);//配送订单
                            cashRecordRide3.setOrderNumber(order.getOrderNumber());
                            cashRecordRide3.setRecoedType(3);//配送订单得钱
                            cashRecordRide3.setMoneyType(2);
                            cashRecordRide3.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                            cashRecordRide3.setMoney(-Double.valueOf(goodsMoney));
                            cashRecordRide3.setStatus(1);//成功
                            cashRecordRide3.setReceivePerson(1);
                            cashRecordRide3.setGivePerson(2);
                            cashRecordDao.save(cashRecordRide3);
                            /*****************在账户流程表中做金额流向记录(代收货款)  商家**********************/
                            CashRecord cashRecordShop2= new CashRecord();
                            cashRecordShop2.setUser(order.getShop());
                            cashRecordShop2.setTitle("配送订单代收货款金额"+goodsMoney+"元");
                            cashRecordShop2.setOrderType(1);//配送订单
                            cashRecordShop2.setOrderNumber(order.getOrderNumber());
                            cashRecordShop2.setRecoedType(4);//消费
                            cashRecordShop2.setMoneyType(1);
                            cashRecordShop2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                            cashRecordShop2.setMoney(Double.valueOf(goodsMoney));
                            cashRecordShop2.setStatus(1);//成功
                            cashRecordShop2.setGivePerson(2);
                            cashRecordShop2.setReceivePerson(1);
                            cashRecordDao.save(cashRecordShop2);
                        }


                    } else {//超过15min骑手不得钱  商家返回所有费用
                   /* BigDecimal totalPrice = new BigDecimal(String.valueOf(sendMoney)).add(new BigDecimal(String.valueOf(tips))).add(new BigDecimal(String.valueOf(changeMoney)));
                    accountShop.setBlockMoney(new BigDecimal(accountShop.getBlockMoney()).subtract(totalPrice).doubleValue());//冻结余额减去这些钱
                   if(n==0){
                       accountShop.setAllMoney(new BigDecimal(accountShop.getAllMoney()).add(totalPrice).add(new BigDecimal(goodsMoney)).doubleValue());
                   }else if(n==1){
                       accountShop.setAllMoney(new BigDecimal(accountShop.getAllMoney()).add(totalPrice).doubleValue());
                   }

                    accountDao.save(accountShop);
                    //骑手押金回归
                    if(n==1){
                        account.setDepositMoney(new BigDecimal(account.getDepositMoney()).add(new BigDecimal(goodsMoney)).doubleValue());
                    }
                    account.setBlockDepositMoney(new BigDecimal(account.getBlockDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
                    accountDao.save(account);
                    if(n==1){
                        *//**************账户资金流水明细(骑手完成订单押金回归)  骑手***************//*
                        CashRecord cashRecordRide= new CashRecord();
                        cashRecordRide.setUser(order.getRide());
                        cashRecordRide.setTitle("订单完成押金回退");
                        cashRecordRide.setOrderType(1);//配送订单
                        cashRecordRide.setOrderNumber(order.getOrderNumber());
                        cashRecordRide.setRecoedType(4);//配送订单得钱
                        cashRecordRide.setMoneyType(2);
                        cashRecordRide.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                        cashRecordRide.setMoney(goodsMoney);
                        cashRecordRide.setStatus(1);//成功
                        cashRecordRide.setReceivePerson(2);
                        cashRecordRide.setGivePerson(2);
                        cashRecordDao.save(cashRecordRide);
                    }
                    *//************账户资金流水明细(所有支付金额回归)  商家***************//*
                    CashRecord cashRecordShop = new CashRecord();
                    cashRecordShop.setUser(order.getShop());
                    cashRecordShop.setTitle("配送订单完成超时返还金额"+totalPrice+"元（全部");
                    cashRecordShop.setOrderType(1);//配送订单
                    cashRecordShop.setOrderNumber(order.getOrderNumber());
                    cashRecordShop.setRecoedType(4);//消费
                    cashRecordShop.setMoneyType(1);
                    cashRecordShop.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                    cashRecordShop.setMoney(totalPrice.doubleValue());
                    cashRecordShop.setStatus(1);//成功
                    cashRecordShop.setGivePerson(1);
                    cashRecordShop.setReceivePerson(1);
                    cashRecordDao.save(cashRecordShop);
                    if(n==0){
                        *//*****************在账户流程表中做金额流向记录(代收货款)  商家**********************//*
                            CashRecord cashRecordShop2= new CashRecord();
                            cashRecordShop2.setUser(order.getShop());
                            cashRecordShop2.setTitle("代收货款");
                            cashRecordShop2.setOrderType(1);//配送订单
                            cashRecordShop2.setOrderNumber(order.getOrderNumber());
                            cashRecordShop2.setRecoedType(4);//消费
                            cashRecordShop2.setMoneyType(1);
                            cashRecordShop2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                            cashRecordShop2.setMoney(goodsMoney);
                            cashRecordShop2.setStatus(1);//成功
                            cashRecordShop2.setGivePerson(2);
                            cashRecordShop2.setReceivePerson(1);
                            cashRecordDao.save(cashRecordShop2);
                    }*/
                    }
                }
                //订单更改为已完成
                order.setOrderStatus(4);
                order.setSendDatetime(new Date());
                orderDao.save(order);
        }

        }finally {
            lock.unlock();//解锁
        }

            //激光推送给商家
//            List<String> aliasList2=new ArrayList<>();
//            aliasList2.add(order.getShop().getAlias());
//            String msg_content2="您有一订单于已成功送达!";
//            JSONObject jsonObject2=new JSONObject();
//            jsonObject2.put("type",5);
//            jsonObject2.put("id",order.getId());
//            int m= JpushShopClientUtil.sendToAliasId(aliasList2,"订单完成通知","订单送达通知",msg_content2,jsonObject2.toString());
//            System.out.print("订单送达消息退推送给商家，消息状态"+m);

        return JsonResp.ok();
    }






    /**
     * @索赔接口（商家端）
     * @param type
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/claimIndemnity",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp claimIndemnity(Long orderId,Long rideId, Integer type) {
        log.debug("索赔接口（商家端）");
        Order order=orderDao.findOne(orderId);
        Double sendMoney = order.getSendMoney();
        Double tips = order.getOrderTip();
//        Double takeMoney = order.getTakeMoney();//代收货款
        Double changeMoney = order.getChangeMoney();//变更费
        Double goodsMoney = order.getGoodsMoney();
        int n=order.getIsIncubatorDelivery();//是否代收
        Account account = accountDao.findByUser(order.getRide());//骑手账户
        Account accountShop = accountDao.findByUser(order.getShop());//商家账户
        Boolean isBack=false;Boolean addBack=false;Boolean cashRecord=false;
        BigDecimal shopAddMoney=null;BigDecimal rideAddMoney=null; BigDecimal totalPrice=null;Integer num=-1;
        //开始加锁
        lock.lock();
        try {
            if(order.getOrderStatus()!=4){
                return  JsonResp.fa("订单有误！");
            }else {
                List<CashRecord> cashRecordList=cashRecordDao.findByUserAndOrderNumber(order.getShop(),order.getOrderNumber());
                for(int i=0,y=cashRecordList.size();i<y;i++){
                    CashRecord cr=cashRecordList.get(i);
                    if(cr.getRecoedType()==7 || cr.getRecoedType()==4 ){
                        return JsonResp.fa("该订单已被处理过,请不要重复操作");
                    }
                }
            }
            if(!String.valueOf(order.getRide().getId()).equals(String.valueOf(rideId))){
                return JsonResp.fa("身份验证错误");
            }else {
                totalPrice = new BigDecimal(String.valueOf(sendMoney)).add(new BigDecimal(String.valueOf(tips))).add(new BigDecimal(String.valueOf(changeMoney)));
                accountShop.setBlockMoney(new BigDecimal(accountShop.getBlockMoney()).subtract(totalPrice).doubleValue());//冻结余额减去这些钱
                account.setBlockDepositMoney(new BigDecimal(account.getBlockDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
                //商家有没有点击索赔 0代表点击1代表未点击
                if(type==0){
                    //订单有有代收货款
                    if(n==0){
                        shopAddMoney=totalPrice.add(new BigDecimal(goodsMoney)).add(new BigDecimal(goodsMoney));
                        rideAddMoney=new BigDecimal(-goodsMoney);
                        addBack=true;//骑手再次扣除货价
                        num=2;
                    }else if(n==1){
                        shopAddMoney=totalPrice.add(new BigDecimal(goodsMoney));
                        rideAddMoney=new BigDecimal("0");
                        cashRecord=true;
                        num=1;
                    }

                }else if(type==1){
                    //订单有代收货款
                    if(n==0){
                        shopAddMoney=totalPrice.add(new BigDecimal(goodsMoney));
                        rideAddMoney=new BigDecimal("0");
                        cashRecord=true;
                        num=1;
                    }else if(n==1){
                        shopAddMoney=totalPrice;
                        rideAddMoney=new BigDecimal(goodsMoney);
                        isBack=true;
                    }
                }
                accountShop.setAllMoney(new BigDecimal(accountShop.getAllMoney()).add(shopAddMoney).doubleValue());
                account.setDepositMoney(new BigDecimal(account.getDepositMoney()).add(rideAddMoney).doubleValue());
                accountDao.save(accountShop);
                accountDao.save(account);
            }

            //-------------------------钱包流水明细--------------
            /**************账户资金流水明细(骑手完成订单押金回归)  骑手***************/
            if(isBack){
                CashRecord cashRecordRide= new CashRecord();
                cashRecordRide.setUser(order.getRide());
                cashRecordRide.setTitle("配送订单解冻金额"+goodsMoney+"元");
                cashRecordRide.setOrderType(1);//配送订单
                cashRecordRide.setOrderNumber(order.getOrderNumber());
                cashRecordRide.setRecoedType(4);//配送订单得钱
                cashRecordRide.setMoneyType(2);
                cashRecordRide.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecordRide.setMoney(goodsMoney);
                cashRecordRide.setStatus(1);//成功
                cashRecordRide.setReceivePerson(2);
                cashRecordRide.setGivePerson(2);
                cashRecordDao.save(cashRecordRide);
            }
            if(addBack){
                CashRecord cashRecordRide= new CashRecord();
                cashRecordRide.setUser(order.getRide());
                cashRecordRide.setTitle("配送订单解冻金额"+goodsMoney+"元");
                cashRecordRide.setOrderType(1);//配送订单
                cashRecordRide.setOrderNumber(order.getOrderNumber());
                cashRecordRide.setRecoedType(4);//配送订单得钱
                cashRecordRide.setMoneyType(2);
                cashRecordRide.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecordRide.setMoney(goodsMoney);
                cashRecordRide.setStatus(1);//成功
                cashRecordRide.setReceivePerson(2);
                cashRecordRide.setGivePerson(2);
                //    cashRecordDao.save(cashRecordRide);

                CashRecord cashRecordRide2= new CashRecord();
                cashRecordRide2.setUser(order.getRide());
                cashRecordRide2.setTitle("配送订单完成超时赔付金额"+goodsMoney+"元");
                cashRecordRide2.setOrderType(1);//配送订单
                cashRecordRide2.setOrderNumber(order.getOrderNumber());
                cashRecordRide2.setRecoedType(3);//配送订单得钱
                cashRecordRide2.setMoneyType(2);
                cashRecordRide2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecordRide2.setMoney(-goodsMoney);
                cashRecordRide2.setStatus(1);//成功
                cashRecordRide2.setReceivePerson(2);
                cashRecordRide2.setGivePerson(2);
                List<CashRecord> cashRecordList=new ArrayList<>();
                cashRecordList.add(cashRecordRide);
                cashRecordList.add(cashRecordRide2);
                cashRecordList.add(cashRecordRide2);
//             cashRecordDao.save(cashRecordRide2);//一定要保存两次
//             cashRecordDao.save(cashRecordRide2);//一定要保存两次
                cashRecordDao.save(cashRecordList);
            }
            if(cashRecord){
                CashRecord cashRecordRide= new CashRecord();
                cashRecordRide.setUser(order.getRide());
                cashRecordRide.setTitle("配送订单解冻金额"+goodsMoney+"元");
                cashRecordRide.setOrderType(1);//配送订单
                cashRecordRide.setOrderNumber(order.getOrderNumber());
                cashRecordRide.setRecoedType(4);//配送订单得钱
                cashRecordRide.setMoneyType(2);
                cashRecordRide.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecordRide.setMoney(goodsMoney);
                cashRecordRide.setStatus(1);//成功
                cashRecordRide.setReceivePerson(2);
                cashRecordRide.setGivePerson(2);
                cashRecordDao.save(cashRecordRide);

                CashRecord cashRecordRide2= new CashRecord();
                cashRecordRide2.setUser(order.getRide());
                cashRecordRide2.setTitle("配送订单超时赔付金额"+goodsMoney+"元");
                cashRecordRide2.setOrderType(1);//配送订单
                cashRecordRide2.setOrderNumber(order.getOrderNumber());
                cashRecordRide2.setRecoedType(3);//配送订单得钱
                cashRecordRide2.setMoneyType(2);
                cashRecordRide2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecordRide2.setMoney(-goodsMoney);
                cashRecordRide2.setStatus(1);//成功
                cashRecordRide2.setReceivePerson(2);
                cashRecordRide2.setGivePerson(2);
                cashRecordDao.save(cashRecordRide2);

            }
            /************账户资金流水明细(所有支付金额回归)  商家***************/
            CashRecord cashRecordShop = new CashRecord();
            cashRecordShop.setUser(order.getShop());
            cashRecordShop.setTitle("配送订单完成超时返还金额"+totalPrice+"元（全部）");
            cashRecordShop.setOrderType(1);//配送订单
            cashRecordShop.setOrderNumber(order.getOrderNumber());
            cashRecordShop.setRecoedType(4);//收入
            cashRecordShop.setMoneyType(1);
            cashRecordShop.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
            cashRecordShop.setMoney(totalPrice.doubleValue());
            cashRecordShop.setStatus(1);//成功
            cashRecordShop.setGivePerson(2);
            cashRecordShop.setReceivePerson(1);
            cashRecordDao.save(cashRecordShop);
            /************账户资金流水明细(货款)  商家***************/
            if(num!=-1){
                CashRecord cashRecordShop2 = new CashRecord();
                cashRecordShop2.setUser(order.getShop());
                BigDecimal goodsMoneyAdd=new BigDecimal(String.valueOf(goodsMoney)).max(new BigDecimal(num)).setScale(1,BigDecimal.ROUND_HALF_UP);
                cashRecordShop2.setTitle("配送订单超时赔付金额"+goodsMoneyAdd+"元");
                cashRecordShop2.setOrderType(1);//配送订单
                cashRecordShop2.setOrderNumber(order.getOrderNumber());
                cashRecordShop2.setRecoedType(7);//收入
                cashRecordShop2.setMoneyType(1);
                cashRecordShop2.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecordShop2.setMoney(goodsMoneyAdd.doubleValue());
                cashRecordShop2.setStatus(1);//成功
                cashRecordShop2.setGivePerson(2);
                cashRecordShop2.setReceivePerson(1);
                cashRecordDao.save(cashRecordShop2);
            }
        }finally {
            lock.unlock();
        }
            return JsonResp.ok();
    }




    /**
     * @保存驳回理由
     * @param order
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/upLoadOrderLog",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp saveOrderLog(@RequestBody Order order) {
        log.debug("保存驳回理由和证据");
        Long orderId=order.getId();
        Order  newOrder=orderDao.findOne(orderId);
        newOrder.setOrderLog(order.getOrderLog());//驳回理由
        newOrder.setOrderLogImg(order.getOrderLogImg());//驳回的图片证据
        orderDao.save(newOrder);
        return JsonResp.ok();
    }


    /**
     * @配送费接口
     * @param shopId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findSendMoney",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findSendMoney(String lat,String lng,Long shopId) {
        log.debug("配送费接口");
        Map map=orderService.findSendMoney(lat,lng,shopId);
        String sendMoney=String.valueOf(map.get("sendMoney"));
        if(sendMoney.equals("-2")){
            return JsonResp.fa("没有查到相关的配送费");
        }else if(sendMoney.equals("-1")){
            return JsonResp.fa("该地区尚未设置开通配送业务");
        }else {
            return JsonResp.ok("配送费",sendMoney);
        }

    }

    /**
     * @获取骑手申请的出货异常处理请求
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findGetOrderException",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findGetOrderException(Long orderId) {
        log.debug("获取骑手申请的出货异常处理请求");
        return JsonResp.ok(orderDao.findOne(orderId));
    }

    /**
     * @商家取消订单（待抢单、待配送、配送中）
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/cancelOrder",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp cancelOrder(Long orderId,Long shopId) {
        log.debug("商家取消订单（待抢单、待配送、配送中）");
        Order order=orderDao.findOne(orderId);
        User ride =order.getRide();
        User shop =order.getShop();
        if(shop.getId().equals(shopId)){ //判断当前用户和商家是否是同一人
            Account accountRide=accountDao.findByUser(ride);//骑手账户
            Account accountShop=accountDao.findByUser(shop);//商家账户
            Double sendMoney = order.getSendMoney();//配送费
            Double tip = order.getOrderTip();//订单小费
            Double takeMoney = order.getTakeMoney();//代收货款
            Double changeMoney=order.getChangeMoney();//变更费
            Double goodsMoney=order.getGoodsMoney();//货物价格
            Integer i=order.getIsIncubatorDelivery();//是否代收
            BigDecimal fSendMoney=null;//流转配送费
            BigDecimal fOrderTip=null;//流转小费
            BigDecimal rideAddMoney=null;//骑手应该加的钱
            BigDecimal  serviceMoney=null;//服务费
            BigDecimal fTotalMoney= new BigDecimal(changeMoney).add(new BigDecimal(sendMoney)).add(new BigDecimal(tip));//总费用
            int orderStatus=order.getOrderStatus();//订单状态
            int type=-1;
            if(orderStatus==1){//如果是待抢单订单
                order.setOrderStatus(8);
                order.setSendDatetime(new Date());//取消订单时间
                accountShop.setAllMoney(new BigDecimal(String.valueOf(accountShop.getAllMoney())).add(fTotalMoney).doubleValue());
                accountShop.setBlockMoney(new BigDecimal(accountShop.getBlockMoney()).subtract(fTotalMoney).doubleValue());
                type=1;
                accountDao.save(accountShop);//保存账户余额
            }else if(orderStatus==2 || orderStatus==5){ //待取货状态取消订单  将其一半配送费和小费转入骑手余额中
                 rideAddMoney=fTotalMoney.multiply(new BigDecimal("0.5")).multiply(new BigDecimal(1-ride.getServiceRate())).setScale(1,BigDecimal.ROUND_HALF_UP);//小费和配送费的一半乘以服务费率
                serviceMoney=fTotalMoney.multiply(new BigDecimal("0.5")).multiply(new BigDecimal(ride.getServiceRate())).setScale(1,BigDecimal.ROUND_HALF_UP);
                Double rideSaveMoney= new BigDecimal(accountRide.getAllMoney()).add(rideAddMoney).doubleValue();
                accountRide.setAllMoney(rideSaveMoney);
                //将货物价格从骑手冻结押金中划回押金中
                accountRide.setDepositMoney(new BigDecimal(accountRide.getDepositMoney()).add(new BigDecimal(goodsMoney)).doubleValue());
                accountRide.setBlockDepositMoney(new BigDecimal(accountRide.getBlockDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
                //将订单支付总费用从 冻结余额中划出
                accountShop.setBlockMoney(new BigDecimal(accountShop.getBlockMoney()).subtract(fTotalMoney).doubleValue());
                //将除去支付给骑手的费用外全部费用流回商家余额
                BigDecimal saveShopAllMoney=fTotalMoney.multiply(new BigDecimal("0.5")).setScale(1,BigDecimal.ROUND_HALF_UP);
                accountShop.setAllMoney(new BigDecimal(accountShop.getAllMoney()).add(saveShopAllMoney).doubleValue());
                accountDao.save(accountRide);//保存到骑手账户余额
                accountDao.save(accountShop);//保存商家账户余额和冻结余额
                order.setOrderStatus(9);
                order.setSendDatetime(new Date());//取消订单时间
                orderDao.save(order);//保存订单
                type=2;
                //激光推送
                List<String> aliasList=new ArrayList<>();
                aliasList.add(ride.getAlias());
                String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                String msg_content="您好，您有一条未配送的订单已被商家取消，取消订单时间:"+time;
                JSONObject jsonObject2=new JSONObject();
                jsonObject2.put("type",8);
                jsonObject2.put("id",order.getId());
                int n=JpushClientUtil.sendToAliasId(aliasList,"商家取消订单通知","取消订单成功",msg_content,jsonObject2.toString());
                log.debug("商家取消订单。。。。。。推送给骑手状态"+n);
            }else if(orderStatus==3 || orderStatus==7){//配送中取消订单  将其全部配送费和全部小费转入骑手余额中
                 rideAddMoney=fTotalMoney.multiply(new BigDecimal(1-ride.getServiceRate())).setScale(1,BigDecimal.ROUND_HALF_UP);///小费和配送费和变更费的乘以服务费率
                serviceMoney=fTotalMoney.multiply(new BigDecimal(ride.getServiceRate())).setScale(1,BigDecimal.ROUND_HALF_UP);
                accountRide.setAllMoney(new BigDecimal(accountRide.getAllMoney()).add(rideAddMoney).doubleValue());
                //将货物价格从骑手冻结押金中划回押金中
                accountRide.setDepositMoney(new BigDecimal(accountRide.getDepositMoney()).add(new BigDecimal(goodsMoney)).doubleValue());
                accountRide.setBlockDepositMoney(new BigDecimal(accountRide.getBlockDepositMoney()).subtract(new BigDecimal(goodsMoney)).doubleValue());
                //将订单支付总费用从 冻结余额中划出
                accountShop.setBlockMoney(new BigDecimal(accountShop.getBlockMoney()).subtract(fTotalMoney).doubleValue());
                accountDao.save(accountShop);
                accountDao.save(accountRide);//保存账户余额
                order.setOrderStatus(10);
                order.setSendDatetime(new Date());//取消订单时间
                orderDao.save(order);//保存订单
                type=3;
                //激光推送
                List<String> aliasList=new ArrayList<>();
                aliasList.add(ride.getAlias());
                String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                String msg_content="您好，您正在配送中的订单已被商家取消，取消订单时间:"+time;
                JSONObject jsonObject2=new JSONObject();
                jsonObject2.put("type",8);
                jsonObject2.put("id",order.getId());
                int n=JpushClientUtil.sendToAliasId(aliasList,"商家取消订单通知","取消订单成功",msg_content,jsonObject2.toString());
                log.debug("商家取消订单。。。。。。。。。。。。。推送给骑手状态"+n);
            }else {
                return  JsonResp.fa("无权取消订单");
            }
            if(type!=1){
                /*****************记录账户明细(余额加钱) 骑手**********************/
                CashRecord cashRecord=new CashRecord();
                cashRecord.setUser(ride);
                String title="";
                if(type==2){
//                    title="商家取消订单，配送费"+new BigDecimal(sendMoney).multiply(new BigDecimal("0.5")).setScale(2,BigDecimal.ROUND_HALF_UP)+
//                            "变更费"+new BigDecimal(changeMoney).multiply(new BigDecimal("0.5")).setScale(2,BigDecimal.ROUND_HALF_UP)+
//                            "小费"+new BigDecimal(tip).multiply(new BigDecimal("0.5")).setScale(2,BigDecimal.ROUND_HALF_UP);
                    title="配送订单取消收款金额"+fTotalMoney.multiply(new BigDecimal("0.5")).setScale(1,BigDecimal.ROUND_HALF_UP)+"元（减半）"+"(平台服务费"+serviceMoney+"元)";
                }else if(type==3){
//                    title="商家取消订单，配送费"+sendMoney+
//                            "变更费"+changeMoney+
//                            "小费"+tip;
                    title="配送订单取消收款金额"+fTotalMoney+"元（全部）"+"(平台服务费"+serviceMoney+"元)";
                }
                cashRecord.setTitle(title);
                cashRecord.setOrderType(1);//配送订单
                cashRecord.setOrderNumber(order.getOrderNumber());
                cashRecord.setRecoedType(4);//配送订单得钱
                cashRecord.setMoneyType(1);
                cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                cashRecord.setMoney(rideAddMoney.doubleValue());
                cashRecord.setStatus(1);//成功
                cashRecord.setGivePerson(1);
                cashRecord.setReceivePerson(2);
                cashRecordDao.save(cashRecord);
                /*****************记录账户明细(押金加钱) 骑手**********************/
                CashRecord depositMoneyCashRecord=new CashRecord();
                depositMoneyCashRecord.setUser(ride);
                depositMoneyCashRecord.setTitle("配送订单解冻金额"+goodsMoney+"元");
                depositMoneyCashRecord.setOrderType(1);//配送订单
                depositMoneyCashRecord.setOrderNumber(order.getOrderNumber());
                depositMoneyCashRecord.setRecoedType(4);//配送订单得钱
                depositMoneyCashRecord.setMoneyType(2);
                depositMoneyCashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                depositMoneyCashRecord.setMoney(goodsMoney);
                depositMoneyCashRecord.setStatus(1);//成功
                depositMoneyCashRecord.setGivePerson(2);
                depositMoneyCashRecord.setReceivePerson(2);
                cashRecordDao.save(depositMoneyCashRecord);
            }
            /*****************记录账户明细（余额加钱） 商家**********************/
            CashRecord cashRecordShop=new CashRecord();
            cashRecordShop.setUser(shop);
            cashRecordShop.setOrderType(1);//配送订单
            cashRecordShop.setOrderNumber(order.getOrderNumber());
            cashRecordShop.setRecoedType(4);//收入
            cashRecordShop.setMoneyType(1);
            cashRecordShop.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
            String title="";
            if(type==1){
                title="配送订单取消返还金额"+fTotalMoney.doubleValue()+"元（全部）";
                cashRecordShop.setTitle(title);
                cashRecordShop.setMoney(fTotalMoney.doubleValue());
            }else if(type==2){
                title="配送订单取消返还金额"+fTotalMoney.multiply(new BigDecimal("0.5").setScale(1,BigDecimal.ROUND_HALF_UP)).doubleValue()+"元（减半）";
                cashRecordShop.setTitle(title);
                cashRecordShop.setMoney(fTotalMoney.multiply(new BigDecimal("0.5").setScale(1,BigDecimal.ROUND_HALF_UP)).doubleValue());
            }else if(type==3){
                title="配送订单取消返还金额0元（扣除）";
                cashRecordShop.setTitle(title);
                cashRecordShop.setMoney(0.0);
            }
            cashRecordShop.setStatus(1);//成功
            cashRecordShop.setReceivePerson(1);
            cashRecordShop.setGivePerson(1);
            cashRecordDao.save(cashRecordShop);
     /*       //激光推送
            List<String> aliasList=new ArrayList<>();
            aliasList.add(shop.getAlias());
            String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            String msg_content="您于"+time+"取消一条订单。";
            JSONObject jsonObject2=new JSONObject();
            jsonObject2.put("type",8);
            jsonObject2.put("id",order.getId());
            int n=JpushShopClientUtil.sendToAliasId(aliasList,"取消订单通知","取消订单成功",msg_content,jsonObject2.toString());*/
        }else {
            return JsonResp.fa("登录身份验证出错!");
        }
        return JsonResp.ok();
    }



    /**
     * @ 获取骑手资料
     * @param rideId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getRideMess",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getRideMess(Long rideId) throws ParseException {
        log.debug("获取骑手资料：手机号、完成订单总量、超时订单数、损坏订单数");
        User user=userdao.findOne(rideId);
        String userName=user.getRealName()==null?"":user.getRealName();
        String head_url=user.getHeadUrl();
        String phone=user.getPhone();
        List<Order>  orderList=orderDao.findByRide(user);
        int totalOrdersNum=0,brokenOrderNum=0,overTimeOrderNum=0;
        for(int i=0;i<orderList.size();i++){
            Order order=orderList.get(i);
            int order_status=order.getOrderStatus();
            Date  send_time=order.getSendTime();//规定送达时间
            Date send_dataTime=order.getSendDatetime();//实际送达时间
            if(send_dataTime==null){
                continue;
            }
            if(order_status==4 ||order_status==6 || order_status==7 ||  order_status==10){
                ++totalOrdersNum;
                if(send_dataTime.after(send_time)){//如果实际送达时间超过规定送达时间 或者 货物损坏
                    ++overTimeOrderNum;
                }
            }
            if("6".equals(order_status)){
                ++brokenOrderNum;
            }
        }
        //将小数转换为百分比
        NumberFormat num = NumberFormat.getPercentInstance();
        num.setMaximumIntegerDigits(3);
        num.setMaximumFractionDigits(2);
        String ontimeDeliveryRate="";
        if(orderList.isEmpty() || totalOrdersNum==0){
            ontimeDeliveryRate=100+"%";
        }else {
            int onTimeOrderNum=totalOrdersNum-overTimeOrderNum;
            ontimeDeliveryRate = num.format(new BigDecimal(onTimeOrderNum).divide(new BigDecimal(totalOrdersNum),2,BigDecimal.ROUND_HALF_UP));
        }
        Map map =new HashMap();
        map.put("userName",userName);
        map.put("headUrl",head_url);
        map.put("phone",phone);
        map.put("overTimeOrderNum",overTimeOrderNum);
        map.put("brokenOrderNum",brokenOrderNum);
        map.put("totalOrdersNum",totalOrdersNum);
        map.put("ontimeDeliveryRate", ontimeDeliveryRate);
        return JsonResp.ok(map);
    }

    /**
     * @ 返回收货异常原因
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/returnExceptLog",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp saveOrderLog(Long orderId) {
        log.debug("返回收货异常原因");
        Order  order=orderDao.findOne(orderId);
        return JsonResp.ok(order.getExceptLog());
    }


    /**
     * @ 订单变更
     * @param order
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/changeOrderMess",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp changeOrderMess(@RequestBody Order order,String sortTypeIds,Integer type,HttpServletRequest request) {
        log.debug("订单变更");
        Long orderId = order.getId();
        Order newOrder = orderDao.findOne(orderId);
        User user=newOrder.getShop();
        Address address = order.getAddressUser();
        if (null == address.getId() || "0".equals(String.valueOf(address.getId()))) {//新增地址
            address = addressDao.save(address);
            newOrder.setAddressUser(address);
        } else {//老地址 比对一下省市区和详细地址  如果地址不同保存新地址  没修改不保存
            Address oldAddress = addressDao.findOne(address.getId());
            if (!oldAddress.equals(address)) {
                address.setId(null);
                address = addressDao.save(address);
                newOrder.setAddressUser(address);
            }
        }
        newOrder.setGoodsMoney(order.getGoodsMoney());
        newOrder.setOrderTip(order.getOrderTip());
        newOrder.setTakeMoney(order.getTakeMoney());
        //变更费 加上之前的变更费
        newOrder.setChangeMoney(new BigDecimal(order.getChangeMoney()).add(new BigDecimal(newOrder.getChangeMoney())).setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue());
        newOrder.setIsRebut(order.getIsRebut());
        newOrder.setOrderMark(order.getOrderMark());
        newOrder.setSendDatetime(new Date());
        //规定送达时间加30分钟
        Long time=newOrder.getSendTime().getTime()+30*60*1000;
        try {
            newOrder.setSendTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //   newOrder.setSendDatetime(new Date());
        newOrder.setIsIncubatorDelivery(order.getIsIncubatorDelivery());
      //  newOrder.setOrderStatus(3);//配送中
        if(newOrder.getOrderStatus()==7){
            newOrder.setOrderStatus(3);//配送中
        }
        orderDao.save(newOrder);
    /*    //保存 货物类型  开始
        String sortTypeId[] = sortTypeIds.split("\\*\\*\\*");
        List<SortBetween> sortBetweenList = new ArrayList<>();
        List<SortBetween> sortBetweenList1=sortBetweenDao.findByTypeAndOrders(1,newOrder);
        for (int i = 0; i < sortTypeId.length; i++) {
            SortBetween sb = new SortBetween();
            if(!sortBetweenList1.isEmpty()){
                int m=0,n=sortBetweenList1.size();
                for (;m<n;m++) {
                    SortBetween sb2=sortBetweenList1.get(m);
                    if(String.valueOf(sb2.getSortTypeId().getId()).equals(sortTypeId[i])){
                        break;
                    }
                }
                if(m!=n){
                   continue;
                }
            }
            sb.setOrders(order);
            SortType st = new SortType();
            st.setId(Long.valueOf(sortTypeId[i]));
            sb.setSortTypeId(st);
            sb.setShop(user);
            sb.setType(1);
            sortBetweenList.add(sb);
        }
        sortBetweenDao.save(sortBetweenList);
        //保存 货物类型 结束*/
      /********************************************支付****************************************************/
        Double changeMoney=order.getChangeMoney()==null?0.0:order.getChangeMoney();//变更费
        BigDecimal payTotalMoney = new BigDecimal(String.valueOf(changeMoney));
        User shop=newOrder.getShop();
            Account account = accountDao.findByUser(shop);
            Double allMoney = account.getAllMoney();//余额
            Double blockMoney=account.getBlockMoney();//冻结余额
            Double depositMoney=account.getDepositMoney();//押金
             String title="";
                if(type==1){//如果用余额支付
                    //账户余额
                    if (new BigDecimal(allMoney).compareTo(payTotalMoney) < 0) {
                        return JsonResp.fa("账户余额不足");
                    }
                    Double saveAllMoney = new BigDecimal(allMoney).subtract(payTotalMoney).doubleValue();
                    Double saveBlockMoney=new BigDecimal(blockMoney).add(payTotalMoney).doubleValue();
                    account.setBlockMoney(saveBlockMoney);//将订单总费用保存到冻结余额中
                    account.setAllMoney(saveAllMoney);
                    accountDao.save(account);
                    title="配送订单变更付款金额"+payTotalMoney+"元";
                    /********************************保存余额支付记录**********************/
                    CashRecord cashRecord = new CashRecord();
                    cashRecord.setUser(shop);
                    cashRecord.setTitle(title);
                    cashRecord.setTransactionNum(OrderUtils.getBalancePayNo());//交易单号
                    //  cashRecord.setOrderNumber();
                    cashRecord.setOrderType(1);//1表示配送订单，2表示商城订单，3表示其他
                    cashRecord.setOrderNumber(newOrder.getOrderNumber());//订单编码
                    cashRecord.setRecoedType(3);//流水类型，1表示充值，2表示提现，3表示消费扣钱
                    cashRecord.setMoney(-payTotalMoney.doubleValue());
                    cashRecord.setMoneyType(1);
                    if(type==1){
                        cashRecord.setPayType(1);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                    }else if(type==2){
                        cashRecord.setPayType(2);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                    }else if(type==3){
                        cashRecord.setPayType(3);//支付类型：1表示余额支付，2表示支付宝支付，3表示微信支付
                    }
                    cashRecord.setStatus(1);
                    cashRecord.setGivePerson(1);
                    cashRecordDao.save(cashRecord);//保存支付记录

                    //激光推送
                    List<String> aliasList=new ArrayList<>();
                    aliasList.add(newOrder.getRide().getAlias());
                    String msg_content="您有订单发生变更，请注意查看。";
                    JSONObject jsonObject2=new JSONObject();
                    jsonObject2.put("type",9);
                    jsonObject2.put("id",order.getId());
                    int n=JpushClientUtil.sendToAliasId(aliasList,"变更订单通知","变更订单",msg_content,jsonObject2.toString());
                    log.debug("商家变更订单。。。。。。。推送状态n="+n);
                    //短信推送用户
                   // String phone=order.getAddressUser().getPhone();
                    JSONArray phones=new JSONArray();
                    phones.put(order.getAddressUser().getPhone());
                    String templateid ="3057409";//订单变更
                    if(phones!=null){
                        try {
                            SmsUtils.sendMsg(phones,templateid,null,3);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }else if(type==3){//微信支付方式

                    String sym = request.getRequestURL().toString().split("/api/")[0];
                    //  Long userId= userService.currentUserId();
                    String trade_no = (order.getId() + "a" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase()).substring(0,32);
                    Map map;
//                    String json=null;
                    map = PayUtils.WxPay(trade_no, payTotalMoney.doubleValue(), "支付", sym + wxnotify3);
                    if (!map.isEmpty()) {
                        //激光推送
                        List<String> aliasList=new ArrayList<>();
                        aliasList.add(newOrder.getShop().getAlias());
                        String msg_content="您有订单发生变更，请注意查看。";
                        JSONObject jsonObject2=new JSONObject();
                        jsonObject2.put("type",9);
                        jsonObject2.put("id",order.getId());
                        int n=JpushShopClientUtil.sendToAliasId(aliasList,"变更订单通知","变更订单",msg_content,jsonObject2.toString());
                        //短信推送用户
                     //   String phone=order.getAddressUser().getPhone();
                        JSONArray phones=new JSONArray();
                        phones.put(order.getAddressUser().getPhone());
                        String templateid ="3057409";//订单变更
                        if(phones!=null){
                            try {
                                SmsUtils.sendMsg(phones,templateid,null,3);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        return JsonResp.ok("成功", map);
                    }else{
                        throw new FailException();
                    }
                }

        return JsonResp.ok(order.getExceptLog());
    }



    /**
     * @删除订单-one(永久)
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteOrderOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteOrderOne(Long orderId) {
        log.debug("删除订单-one(永久)");
        orderDao.delete(orderId);
        return JsonResp.ok();
    }

    /**
     * @订单列表 （待配送、配送中、已取消）
     * @param orderStatus
     * pageNum 第几页
     * pageSize 每页多少数据
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getOrderListByOrderStatus",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getOrderListByOrderStatus(Integer orderStatus,Long userId,Integer pageNum, Integer pageSize) throws Exception {
        log.debug("订单列表 （待配送、配送中、已取消）");
        User user = userdao.findOne(userId);
        List<Integer> orderStatusList=new ArrayList<>();
        if(orderStatus==3){
            orderStatusList.add(3);
            orderStatusList.add(7);
        }else if(orderStatus==2){
            orderStatusList.add(5);
            orderStatusList.add(2);
        }else if(orderStatus==9){
            orderStatusList.add(9);
            orderStatusList.add(10);
        }
     //   List<Order> orderList = orderDao.findByRideAndOrderStatusIn(user, orderStatusList);
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        page = orderDao.findAll( 		  //条件分页
                (root, criteriaQuery, cb) -> {
                    Predicate predicate = cb.conjunction();
                    List<Expression<Boolean>> expressions = predicate.getExpressions();
                    expressions.add(cb.equal(root.get("ride"), user));
                    CriteriaBuilder.In<Object> stick = cb.in(root.get("orderStatus"));
                    for (Integer l : orderStatusList) {
                        expressions.add(stick.value(l));
                    }
                    return predicate;
                }, pageable);
        List<Order> content = page.getContent();
        for (Order order : content) {
            order.setNowTime(new Date().getTime());
        }
        return JsonResp.ok(new PageDto(page));

    }


    /**
     * @订单详情（待配送、配送中、已取消）
     * @param  orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getOrderDetailUnderRide",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getOrderDetailUnderRide(long orderId) {
        log.debug("订单详情（待配送、配送中、已取消）");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Order order = orderDao.findOne(orderId);
        Map map = new HashMap();
        User shop=order.getShop();
        User ride=order.getRide();
        Address addressShop = order.getAddressShop();
        Address addressUser = order.getAddressUser();
        Address  addressRide=addressDao.findOne(ride.getAddress());
        StrBuilder strAddressShop = new StrBuilder();
        StrBuilder strAddressUser = new StrBuilder();
        strAddressShop.append(addressShop.getProvince());
        strAddressShop.append(addressShop.getCity());
        strAddressShop.append(addressShop.getCounty());
        strAddressShop.append(addressShop.getAddressDetail());
        strAddressUser.append(addressUser.getProvince());
        strAddressUser.append(addressUser.getCity());
        strAddressUser.append(addressUser.getCounty());
        strAddressUser.append(addressUser.getAddressDetail());
        map.put("sendTime", sdf.format(order.getSendTime()));
        map.put("currentTime", sdf.format(new Date()));
        map.put("orderId", order.getId());
        map.put("addressShop", strAddressShop.toString());//取货地址
        map.put("addressShopLng", addressShop.getLng());//取货地址经度
        map.put("addressShopLat", addressShop.getLat());//取货地址维度
        map.put("addressUser", strAddressUser.toString());//收货地址
        map.put("addressUserLng", addressUser.getLng());//收货地址经度
        map.put("addressUserLat", addressUser.getLat());//收货地址维度
        map.put("addressRideLng", addressRide.getLng());//骑手地址经度
        map.put("addressRideLat", addressRide.getLat());//骑手地址维度
        map.put("heardUrl", ride.getSecondId());//骑手头像
        map.put("userPhone",addressUser.getPhone());
        map.put("shopPhone",addressShop.getPhone());
        //获取商家店铺信息 店铺图片  名字  准时出货率
        Map shopMap=new HashMap();
        shopMap.put("shopHeadUrl",shop.getHeadUrl());
        shopMap.put("shopNickName",shop.getNickName());
        shopMap.put("storeUrl",shop.getStoreUrl());
        /*************获取商家准时出货率 开始*******************/
        String  onTimeDeliveryRate=orderService.findOntimeDeliveryRate(shop);
        shopMap.put("onTimeDeliveryRate",onTimeDeliveryRate);
        /*************获取商家准时出货率 结束*******************/
        map.put("realName", addressUser.getRealName());//客户真实名字
        map.put("status", addressUser.getStatus());//地址状态
        map.put("sex", addressUser.getSex());//客户性别
        map.put("sendMoney", order.getSendMoney());
        map.put("changeMoney", order.getChangeMoney());
        map.put("orderTip", order.getOrderTip());
        map.put("takeMoney", order.getTakeMoney());
        map.put("goodsMoney", order.getGoodsMoney());
        map.put("orderNumber", order.getOrderNumber());
        map.put("incubatorDelivery", order.getIsIncubatorDelivery());
        map.put("orderMark", order.getOrderMark());//订单备注
        map.put("distance", order.getDistance());//订单备注
        map.put("dayOrderIndex", order.getDayOrderIndex());//日订单序号
        map.put("isTakeExcept", order.getIsTakeExcept()==null ? 0:order.getIsTakeExcept());//是否取货异常，0标识正常，1标识异常
        map.put("isSendExcept", order.getIsSendExcept()==null ? 0:order.getIsSendExcept());//是否收货异常，0标识正常，1标识异常
        Date getDatetime=order.getGetDatetime();//取货时间
        if(getDatetime==null){
            map.put("getDatetime", null);
        }else {
            map.put("getDatetime", sdf.format(getDatetime));
        }
        Date robDatetime=order.getRobDatetime();//抢单时间
        if(robDatetime==null){
            map.put("robDatetime", null);
        }else {
            map.put("robDatetime",sdf.format(robDatetime) );
        }
        Date sendDatetime=order.getSendDatetime();//送达时间
        if(sendDatetime==null){
            map.put("sendDatetime", null);
        }else {
            map.put("sendDatetime", sdf.format(sendDatetime));
        }
       Date uptDatetime=order.getUptDatetime();//修改时间
        if(uptDatetime==null){
            map.put("uptDatetime", null);
        }else {
            map.put("uptDatetime",sdf.format(uptDatetime) );
        }
        map.put("shopMessageMap",shopMap);//商家店铺信息
        List<String> strList = new ArrayList<>(); //获取货物类型
        List<SortBetween> sortBetweenList = sortBetweenDao.findByOrders(order);
        for (int i = 0; i < sortBetweenList.size(); i++) {
            SortType sortType = sortBetweenList.get(i).getSortTypeId();
            strList.add(sortType.getSortName());
        }
        map.put("sortNameList", strList);
        return JsonResp.ok(map);
    }

    /**
     * @上传出货异常
     * @param order
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/saveExceptionOrderMessage",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp saveExceptionOrderMessage(@RequestBody Order order,Integer type) {
        log.debug("上传出货异常");
        Order order1 = orderDao.findOne(order.getId());
        if (type == 1) {//骑手要求商家取消订单
            order1.setIsCancelOrder(1);
            order1.setIsTakeExcept(1);
            order1.setOrderStatus(5);//出货异常
            order1.setSendDatetime(new Date());
        } else if (type == 2) {
            if (order1.getOrderStatus() == 2) {//只有待取货状态才能申报出货异常
                order1.setIsTakeExcept(1);
                order1.setOrderStatus(5);//出货异常
                order1.setAddSendTime(order.getAddSendTime());
                order1.setAddSendMoney(order.getAddSendMoney());
                order1.setSendDatetime(new Date());
                order1.setIsCancelOrder(2);
            }
            orderDao.save(order1);
            //激光推送
            List<String> aliasList = new ArrayList<>();
            aliasList.add(order1.getShop().getAlias());
            JSONObject jsonObject2 = new JSONObject();
            jsonObject2.put("type", 2);
            jsonObject2.put("id", order.getId());
            String msg_content = "您有订单存在取货异常，请尽快处理";
            int n = JpushShopClientUtil.sendToAliasId(aliasList, "取货异常通知", "取货异常", msg_content, jsonObject2.toString());
            System.out.print("骑手上报出货异常，推送消息状态n=" + n);
            log.debug("骑手上报出货异常，推送消息状态n=" + n);
            //短信推送用户
            //  String phone=order1.getAddressUser().getPhone();
            JSONArray phones = new JSONArray();
            phones.put(order1.getAddressUser().getPhone());
            String templateid = "3060371";//出货异常
            if (phones != null) {
                try {
                    SmsUtils.sendMsg(phones, templateid, null, 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else  {
            return JsonResp.fa("您已经申报过出货异常");
        }
        return JsonResp.ok();
    }
    /**
     * @取消上传出货异常
     * @param orderId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/CancelSaveExceptionOrder",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp CancelSaveExceptionOrder(Long orderId) {
        log.debug("取消上传出货异常");
        Order order=orderDao.findOne(orderId);
        if(order.getOrderStatus()!=5){
            return JsonResp.fa("商家已对该异常订单做过处理，取消异常失败！");
        }else {
            order.setIsTakeExcept(0);
            order.setAddSendMoney(0d);
            order.setAddSendMoney(0d);
            order.setIsCancelOrder(2);
            order.setOrderStatus(3);//状态更改为配送中
            order.setGetDatetime(new Date());
            orderDao.save(order);
        }
        return JsonResp.ok();
    }



    /**
     * @抢单中心
     * @param status
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/getAllOrderListByOrderStatus",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp getAllOrderListByOrderStatus(Integer status,String lng,String lat,Integer pageNum, Integer pageSize) {
        log.debug("抢单中心");
        String sql= "SELECT \n" +
                    "  a.id,\n" +
                    "  FORMAT(6378.138 * 2 * ASIN(SQRT(POW(SIN(\n" +
                    "    (\n" +lat+"*PI()/180-b.lat*PI()/180)/2),2)+\n" +
                    "      COS(\n" +lat+"*PI()/180)*COS(b.lat*PI()/180)*POW(SIN(("+lng+"*PI()/180-b.lng*PI()/180)/2),2)\n" +
                    "      )\n" +
                    "    ),\n" +
                    "    2\n" +
                    "  ) AS distance FROM address b,user a\n"+
                    " where a.address=b.id and b.status=1 and b.type=2";
        Query query = entityManager.createNativeQuery(sql);
        entityManager.close();
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));
        List<Long> idList=new ArrayList<>();
         for(Map map:mapList){
             if(Double.valueOf(String.valueOf(map.get("distance"))).compareTo(Double.valueOf(3))<=0){
                 idList.add(Long.valueOf(String.valueOf(map.get("id"))));
             }
         }
        List<User> userList=userdao.findByIdIn(idList);


        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        page = orderDao.findAll( 		  //条件分页
                (root, criteriaQuery, cb) -> {
                    Predicate predicate = cb.conjunction();
                    List<Expression<Boolean>> expressions = predicate.getExpressions();
                    expressions.add(cb.equal(root.get("orderStatus"), status));
                    CriteriaBuilder.In<Object> stick = cb.in(root.get("shop"));
                    for (User l : userList) {
                        expressions.add(stick.value(l));
                    }
                    return predicate;
                }, pageable);
        List<Order> orderList = page.getContent();
      //  List<Order> orderList=orderDao.findByShopInAndOrderStatus(userList,status);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<Map> orderMapList=new ArrayList<>();
        for(int i=0,y=orderList.size();i<y;i++){
            Map map=new HashMap();
            Order order=orderList.get(i);
            User user=order.getShop();
            Address addressShop=order.getAddressShop();
            Address addressUser=order.getAddressUser();
            StringBuilder strAddressShop=new StringBuilder();
            StringBuilder  strAddressUser=new StringBuilder();
            strAddressShop.append(addressShop.getProvince());
            strAddressShop.append(addressShop.getCity());
            strAddressShop.append(addressShop.getCounty());
            strAddressShop.append(addressShop.getAddressDetail());
            strAddressUser.append(addressUser.getProvince());
            strAddressUser.append(addressUser.getCity());
            strAddressUser.append(addressUser.getCounty());
            strAddressUser.append(addressUser.getAddressDetail());
            map.put("storeUrl",user.getStoreUrl());//商家店面照
            map.put("headUrl",user.getHeadUrl());//商家店铺头像
            /*************获取商家准时出货率 开始*******************/
            String onTimeDeliveryRate=orderService.findOntimeDeliveryRate(user);
            map.put("onTimeDeliveryRate",onTimeDeliveryRate);
            /*************获取商家准时出货率 结束*******************/
            map.put("currentTime",sdf.format(new Date()));
            map.put("orderId",order.getId());
            map.put("addressShop",strAddressShop.toString());//取货地址
            map.put("addressShopLng",addressShop.getLng());//取货地址经度
            map.put("addressShopLat",addressShop.getLat());//取货地址维度
            map.put("addressUser",strAddressUser.toString());//收货地址
            map.put("addressUserLng",addressUser.getLng());//收货地址经度
            map.put("addressUserLat",addressUser.getLat());//收货地址维度
            map.put("realName",addressUser.getRealName());//客户真实名字
            map.put("shopNickName",user.getNickName());//店铺名字
            map.put("status",addressUser.getStatus());//地址状态
            map.put("sex",addressUser.getSex());//客户性别
            map.put("sendMoney",order.getSendMoney());
            map.put("changeMoney",order.getChangeMoney());
            map.put("orderTip",order.getOrderTip());
            map.put("goodsMoney",order.getGoodsMoney());
            map.put("distance",order.getDistance());
            map.put("incubatorDelivery",order.getIsIncubatorDelivery());
            map.put("takeMoney",order.getTakeMoney());
      //      map.put("orderNumber",order.getOrderNumber());
            map.put("orderMark",order.getOrderMark());//订单备注
//            map.put("getDatetime",order.getGetDatetime());//取货时间
//            map.put("robDatetime",order.getRobDatetime());//抢单时间
//            map.put("sendDatetime",order.getSendTime());//送达时间
//            map.put("uptDatetime",order.getUptDatetime());//修改时间
            List<String> strList=new ArrayList<>(); //获取货物类型
            List<SortBetween> sortBetweenList=sortBetweenDao.findByOrders(order);
            for(int m=0;m<sortBetweenList.size();m++){
                SortType sortType=sortBetweenList.get(m).getSortTypeId();
                strList.add(sortType.getSortName());
            }
            map.put("sortNameList",strList);
            orderMapList.add(map);
        }
        PageDto page1=new PageDto(page);
        page1.setList(orderMapList);
        return JsonResp.ok(page1);
        //return JsonResp.ok(orderMapList);
    }



    /**
     * @批量删除订单(永久)
     * @param orders
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomeOrder",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomeOrder(@RequestBody List<Order> orders) {
        log.debug("批量删除订单(永久)");
        orderDao.delete(orders);
        return JsonResp.ok();
    }


    /**
     * @消息推送接口（3公里以内如果有新建订单，会把该新建订单推送给骑手）
     * @param rideId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/ridePush",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp ridePush(String lng,String lat,Long rideId) {
        log.debug("消息推送接口");
   /*     String sql = "SELECT \n" +
                "  a.id,\n" +
                "  FORMAT(6378.138 * 2 * ASIN(SQRT(POW(SIN(\n" +
                "    (\n" + lat + "*PI()/180-b.lat*PI()/180)/2),2)+\n" +
                "      COS(\n" + lat + "*PI()/180)*COS(b.lat*PI()/180)*POW(SIN((" + lng + "*PI()/180-b.lng*PI()/180)/2),2)\n" +
                "      )\n" +
                "    ),\n" +
                "    2\n" +
                "  ) AS distance FROM address b,user a\n" +
                " where a.address=b.id and b.status=1 and b.type=2";
        Query query = entityManager.createNativeQuery(sql);
        entityManager.close();
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));
        List<Long> idList = new ArrayList<>();
        for (Map map : mapList) {
            if (Double.valueOf(String.valueOf(map.get("distance"))).compareTo(Double.valueOf(3)) <= 0) {
                idList.add(Long.valueOf(String.valueOf(map.get("id"))));
            }
        }
        List<User> userList = userdao.findByIdIn(idList);
        List<Order> orderList = orderDao.findByShopInAndOrderStatus(userList, 1);
        List<Order> pushOrderList = new ArrayList<>();
        for (int i = 0, y = orderList.size(); i < y; i++) {
            Order order = orderList.get(i);
            Long gmtDatetime = order.getGmtDatetime().getTime();//订单产生时间
            Long fiveMinBefore = System.currentTimeMillis() - 5 * 1000;//5分钟前
            if (gmtDatetime >= fiveMinBefore) {//如果订单是不是在5分钟前产生的
                pushOrderList.add(order);
            }
        }*/
        //----------------------5min记录一次骑手当前位置--------------------
        User user = userdao.findOne(rideId);
        Address address=addressDao.findByIdAndStatus(user.getAddress(),1);
        DynamicPlace dynamicPlace=new DynamicPlace();
        dynamicPlace.setAreaCode(address.getAreaCode());
        dynamicPlace.setLng(lng);
        dynamicPlace.setLat(lat);
        dynamicPlace.setRideId(rideId);
        dynamicPlaceDao.save(dynamicPlace);
        //--------------------------------消息推送----------------------
        int n = 0;
//        if (!pushOrderList.isEmpty()) {
//            //激光推送
//            List<String> aliasList = new ArrayList<>();
//            aliasList.add(user.getAlias());
//            String msg_content = "有新的快百克订单产生";
//            JSONObject jsonObject2 = new JSONObject();
//            jsonObject2.put("type", 10);
//            jsonObject2.put("orderList", pushOrderList);
//            n = JpushClientUtil.sendToAliasId(aliasList, "新建订单通知", "新订单产生", msg_content, jsonObject2.toString());
//        }
        return JsonResp.ok(n);
    }


    /**
     * @1min获取一次骑手位置
     * @param rideId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findRideSizeOneMin",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findRideSizeOneMin(Long rideId) {
        log.debug("消息推送接口");
        //----------------------1min获取一次骑手当前位置--------------------
        String sql = "select lng,lat,area_code,ride_id,id from dynamic_place where ride_id="+rideId+" order by gmt_datetime desc limit 1";
        Query query = entityManager.createNativeQuery(sql);
        entityManager.close();
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<DynamicPlace> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), DynamicPlace.class)));
        return JsonResp.ok(mapList);
    }

    /**
     * @分页查询订单列表(jpa方式)
     * @param orderStatus 分页条件
     * @param search 模糊搜索
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageOrderJpa(Integer orderStatus, Integer pageNum, Integer pageSize,String search) {
        log.debug("分页查询订单列表(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
        Page page = null;
        if (null == orderStatus) {
            page = orderDao.findAll(pageable); //无条件分页
        } else {
            page = orderDao.findAll(          //条件分页
                    (root, query, cb) -> {
                        Predicate p = cb.and(cb.isNotNull(root.get("id")));
                        if (orderStatus == -1) {
                            List<Integer> statuses = new ArrayList<Integer>() {{
                                add(4);
                                add(6);
                            }};
                            p = cb.and(p, cb.in(root.get("orderStatus")).value(statuses));
                        } else if (orderStatus == -2) {
                            List<Integer> statuses = new ArrayList<Integer>() {{
                                add(8);
                                add(9);
                                add(10);
                            }};
                            p = cb.and(p, cb.in(root.get("orderStatus")).value(statuses));
                        } else {
                            p = cb.and(p, cb.equal(root.get("orderStatus"), orderStatus));
                        }
                        //判断模糊查询是否为数字
                        Pattern pattern = Pattern.compile("[0-9]*");
                        if (pattern.matcher(search).matches() == true) {
                            p = cb.and(p, cb.like(root.get("orderNumber"), "%" + search + "%"));
                        }
                        List<User> shops = userdao.findByNickNameLikeOrRealNameLikeAndUserType("%" + search + "%", "%" + search + "%", 3);
                        List<Long> ids = shops.stream().map(User::getId).collect(Collectors.toList());
                        List<User> rides = userdao.findByNickNameLikeOrRealNameLikeAndUserType("%" + search + "%", "%" + search + "%", 2);
                        List<Long> ids1 = rides.stream().map(User::getId).collect(Collectors.toList());
                        if ((shops == null || shops.isEmpty()) && (rides == null || rides.isEmpty())) {
                            p = cb.and(p, cb.or(cb.in(root.get("shop")).value(0), cb.in(root.get("ride")).value(0)));
                        }
                        p = cb.and(p, cb.or(cb.in(root.get("shop")).value(ids), cb.in(root.get("ride")).value(ids1)));
                        return p;
                    }, pageable);
        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @分页查询(原生sql)
     * @param orderStatus 订单状态
     * @param search 模糊搜索
     * @param pageNum 第几页
     * @param pageSize 每页的条数page
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/sqlPage",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageOrderSql(Integer pageNum, Integer pageSize,Integer orderStatus,String search,String startTime,String endTime) {
        log.debug("分页查询(原生sql)");

/*        List<User> users = userdao.findByNickNameOrRealNameLike("%"+search+"%","%"+search+"%");
        String sql0 = " (";
        for (int i = 0; i < users.size(); i++) {
            if (i == (users.size()-1)) {
                sql0 += users.get(i).getId();
            }else{
                sql0 += users.get(i).getId() + ",";
            }
        }
        sql0 += ") ";*/
        //找到指派时间
        List<CallSetting> list = callSettingDao.findAll();
        CallSetting callSetting = list.get(0);
        Integer time = callSetting.getCallTime();

        String startTime1=null;
        String endTime1=null;
        if(!startTime.isEmpty()&&!endTime.isEmpty()){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startTime1=sdf.format(sdf.parse(startTime));
                endTime1=sdf.format(sdf.parse(endTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startTime1=sdf.format(sdf.parse("1900-01-01"));
                endTime1=sdf.format(sdf.parse("2100-01-01"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String sql;
        if (orderStatus == -4) {
            sql = "FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.is_take_except = 1 AND (o.order_number LIKE '%" + search + "%'OR s.nick_name LIKE '%" + search + "%'OR s.real_name LIKE '%" + search + "%'OR r.nick_name LIKE '%" + search + "%'OR r.real_name LIKE '%" + search + "%') ORDER BY o.gmt_datetime DESC ";
        }else if (orderStatus == -3) {
            sql = "FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.order_status = 1 And (SELECT (UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(o.gmt_datetime))/60)> " + time + " AND (o.order_number LIKE '%" + search + "%'OR s.nick_name LIKE '%" + search + "%'OR s.real_name LIKE '%" + search + "%'OR r.nick_name LIKE '%" + search + "%'OR r.real_name LIKE '%" + search + "%') ORDER BY o.gmt_datetime DESC";
        } else if (orderStatus == -1) {
            sql = "FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.order_status in(4,6) AND (o.order_number LIKE '%" + search + "%'OR s.nick_name LIKE '%" + search + "%'OR s.real_name LIKE '%" + search + "%'OR r.nick_name LIKE '%" + search + "%'OR r.real_name LIKE '%" + search + "%') AND o.gmt_datetime BETWEEN '"+startTime1+"' AND '"+endTime1+"' ORDER BY o.gmt_datetime DESC" ;
        } else if (orderStatus == -2) {
            sql = "FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.order_status in(8,9,10) AND (o.order_number LIKE '%" + search + "%'OR s.nick_name LIKE '%" + search + "%'OR s.real_name LIKE '%" + search + "%'OR r.nick_name LIKE '%" + search + "%'OR r.real_name LIKE '%" + search + "%')  AND o.gmt_datetime BETWEEN '"+startTime1+"' AND '"+endTime1+"' ORDER BY o.gmt_datetime DESC" ;
        } else {
            sql = "FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.order_status = " + orderStatus + " AND (o.order_number LIKE '%" + search + "%'OR s.nick_name LIKE '%" + search + "%'OR s.real_name LIKE '%" + search + "%'OR r.nick_name LIKE '%" + search + "%'OR r.real_name LIKE '%" + search + "%') ORDER BY o.gmt_datetime  DESC";
        }

/*        if (users != null && !users.isEmpty()) {
            sql += " or orders.shop in " + sql0 + " or orders.ride in " + sql0 ;
        }
        sql += " ) ";*/

        Query query = entityManager.createNativeQuery("SELECT o.id AS id,o.order_number AS number,o.gmt_datetime AS time,s.nick_name AS shopname,r.real_name AS ridename,a.address_detail AS detail,o.order_status AS status,o.take_money AS take,o.send_money AS send,o.order_tip as tip,o.change_money as changemoney,o.order_mark AS mark " + sql);

        BigInteger count_number = null;
        //总记录数
        Query query_number = entityManager.createNativeQuery("SELECT COUNT(1) " + sql);
        count_number = (BigInteger) query_number.getSingleResult();
        long total = count_number.longValue();
        //分页
        if ((pageNum - 1) >= 0) {
            query.setFirstResult((pageNum - 1) * pageSize);
        }
        if (pageSize > 0) {
            query.setMaxResults(pageSize);
        }
        entityManager.close();

        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<Map> mapList = new ArrayList<>();
        query.getResultList().forEach(n -> mapList.add(PubLib.copyObject(PubLib.convert(n), Map.class)));
        return JsonResp.ok(new PageDto(pageNum, pageSize, mapList, total));


    }

    /**
     * @查看订单详情
     * @param id 订单id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/orderDetils",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findDetilsById(Long id) {
        log.debug("查看订单详情");
        return JsonResp.ok( orderDao.findOne(id));

    }

    /**
     * @param search 模糊查询
     * @param orderStatus 订单状态
     * @return 返回值JsonResp
     * @订单总计工具栏
     */
    @RequestMapping(value = "/orderSum",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp OrderSum(Integer orderStatus,String search ,String startTime,String endTime) {
        log.debug("订单总计工具栏");
        //找到指派时间
        List<CallSetting> list = callSettingDao.findAll();
        CallSetting callSetting = list.get(0);
        Integer time = callSetting.getCallTime();
        //处理时间
        String startTime1=null;
        String endTime1=null;
        if(!startTime.isEmpty()&&!endTime.isEmpty()){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startTime1=sdf.format(sdf.parse(startTime));
                endTime1=sdf.format(sdf.parse(endTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startTime1=sdf.format(sdf.parse("1900-01-01"));
                endTime1=sdf.format(sdf.parse("2100-01-01"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String sql;
        if(orderStatus==-1){
            sql=" SELECT SUM(o.take_money) as takemoney, SUM(o.send_money) as sendmoney,SUM(o.order_tip) AS tip,SUM(o.change_money) AS changemoney FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.order_status in(4,6) AND (o.order_number LIKE '%"+search+"%'OR s.nick_name LIKE '%"+search+"%'OR s.real_name LIKE '%"+search+"%'OR r.nick_name LIKE '%"+search+"%'OR r.real_name LIKE '%"+search+"%') AND o.gmt_datetime BETWEEN '"+startTime1+"' AND '"+endTime1+"'";
        }else if(orderStatus==-2){
            sql=" SELECT SUM(o.take_money) as takemoney, SUM(o.send_money) as sendmoney,SUM(o.order_tip) AS tip,SUM(o.change_money) AS changemoney FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.order_status in(8,9,10) AND (o.order_number LIKE '%"+search+"%'OR s.nick_name LIKE '%"+search+"%'OR s.real_name LIKE '%"+search+"%'OR r.nick_name LIKE '%"+search+"%'OR r.real_name LIKE '%"+search+"%') AND o.gmt_datetime BETWEEN '"+startTime1+"' AND '"+endTime1+"' ";
        }else if(orderStatus==-3){
            sql=" SELECT SUM(o.take_money) as takemoney, SUM(o.send_money) as sendmoney,SUM(o.order_tip) AS tip,SUM(o.change_money) AS changemoney FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.order_status = 1 And (SELECT (UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(o.gmt_datetime))/60)> " + time + " AND (o.order_number LIKE '%" + search + "%'OR s.nick_name LIKE '%" + search + "%'OR s.real_name LIKE '%" + search + "%'OR r.nick_name LIKE '%" + search + "%'OR r.real_name LIKE '%" + search + "%') ";
        }else if(orderStatus==-4){
            sql=" SELECT SUM(o.take_money) as takemoney, SUM(o.send_money) as sendmoney,SUM(o.order_tip) AS tip,SUM(o.change_money) AS changemoney FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE  o.is_take_except = 1 AND (o.order_number LIKE '%" + search + "%'OR s.nick_name LIKE '%" + search + "%'OR s.real_name LIKE '%" + search + "%'OR r.nick_name LIKE '%" + search + "%'OR r.real_name LIKE '%" + search + "%') ";
        }
        else{
            sql=" SELECT SUM(o.take_money) as takemoney, SUM(o.send_money) as sendmoney ,SUM(o.order_tip) AS tip,SUM(o.change_money) AS changemoney FROM orders o LEFT JOIN `user` s ON o.shop = s.id LEFT JOIN `user` r ON o.ride = r.id LEFT JOIN address a ON o.address_user = a.id WHERE o.order_status = "+orderStatus +" AND (o.order_number LIKE '%"+search+"%'OR s.nick_name LIKE '%"+search+"%'OR s.real_name LIKE '%"+search+"%'OR r.nick_name LIKE '%"+search+"%'OR r.real_name LIKE '%"+search+"%') ";
        }
        Object resultList = sqlToResult.getResultList(sql, "one");
        Map map = PubLib.copyObject(resultList, Map.class);
        return JsonResp.ok(map);

    }
    /**
     * @分页查询单个用户历史订单(jpa方式)
     * @param userId 分页条件
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/pageByUser",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPageOrderJpaByUser(Long userId, Integer pageNum, Integer pageSize) {
        log.debug("分页查询单个用户历史订单(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == userId) {
        }else{
            page = orderDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        User user = userdao.findOne(userId);
                        if(user.getUserType()==3) {
                            expressions.add(cb.equal(root.get("shop"), user));
                        }else if(user.getUserType()==2){
                            expressions.add(cb.equal(root.get("ride"), user));
                        }
                        return predicate;
                    }, pageable);
        }
        return JsonResp.ok(new PageDto(page));
    }


    /**
     * @分页查询已驳回订单(jpa方式)
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/refuseOrderPage",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findrefuseOrderPage( Integer pageNum, Integer pageSize) {
        log.debug("分页查询已驳回订单(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = orderDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        expressions.add(cb.equal(root.get("isRebut"),0));
                        return predicate;
                    }, pageable);
        return JsonResp.ok(new PageDto(page));
    }
    /**
     * @return 返回值JsonResp
     * @所有指派订单
     */
    @RequestMapping(value = "/allSendOrders",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp allSendOrders(Long rideId) {
        log.debug("所有指派订单");
        //找到指派时间
        List<CallSetting> list = callSettingDao.findAll();
        CallSetting callSetting =list.get(0);
        Integer time=callSetting.getCallTime();
        String sql="SELECT * FROM orders WHERE order_status = 1 And (SELECT (UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(gmt_datetime))/60)> "+time+" ";
        List resultList = (List)sqlToResult.getResultList(sql);
        List<Map> maps=new ArrayList<>();
        for (Object o : resultList) {
            Map map=PubLib.copyObject(o, Map.class);
            maps.add(map);
        }
        return JsonResp.ok(maps);
    }

    /**
     * @return 返回值JsonResp
     * @返回某个用户所有订单（微信端）
     */
    @RequestMapping(value = "/myOrderList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp myOrderList(Integer type,String phone) {
        log.debug("返回某个用户所有订单");
        User user=userService.currentUser();
        log.debug("用户电话phone"+user.getPhone());
        List<Address> addresses=addressDao.findByPhone(user.getPhone());
        List<Integer> orderStatusList=new ArrayList<>();
        List<Order> orderList=null;
      if(type==1){//未完成订单
          orderStatusList.add(1);
          orderStatusList.add(2);
          orderStatusList.add(3);
          orderStatusList.add(5);
          orderList=orderDao.findByOrderStatusInAndAddressUserIn(orderStatusList,addresses);
      }else if(type==2){//历史订单
          orderList=orderDao.findByAddressUserIn(addresses);
          List<Order> orders=new ArrayList<>();
          SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
          for (Order order:orderList ) {
              Date grmDate=order.getGetDatetime();
              if(grmDate==null){
                  continue;
              }
              if(java.sql.Date.valueOf(sdf.format(grmDate)).before(java.sql.Date.valueOf(sdf.format(new Date()))) || order.getOrderStatus()==4){
                  orders.add(order);
              }
          }
          return JsonResp.ok(orders);
      }
        return JsonResp.ok(orderList);
    }
    /**
     * @return 返回值JsonResp
     * @获取订单详情（微信端）
     */
    @RequestMapping(value = "/findOrderDetail",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findOrderDetail(Long orderId) {
        log.debug("获取订单详情（微信端）");
       Order order=orderDao.findOne(orderId);
        return JsonResp.ok(order);
    }


}



